/**
 * Common MySBX utility scripts that apply to almost all page contexts
 */

var submitFlag = false;

if (Drupal.jsEnabled) {
  $(document).ready (function() {
    // Simplified menu hovers (jschleiden)
    initMenus ();
    initFormHelp ();
    // Prevent directy form check for SUBMIT action by setting a flag
    $("input:submit").bind ('click', function() {submitFlag = true;});
    sbx_bind_help_article_links ();
  });

  $(window).unload( function () {
    // Dirty form check while window unload (page unload)
    return on_unload_dirty_form_check ();
  });

  // wait till after images load to fix them
  $(window).load(function() {
    // Adjust non-square avatar image displays
    sbx_fix_non_square_image_size ();

 });
}

function sbx_bind_help_article_links () {
  $('a.mysbxHelpArticleLink').each ( function () {
    var url = $(this).attr ('href');
    var title = $(this).attr ('title');
    var options = $(this).attr ('options');
    if (!options)  {
      options = "width=550,height=550,resizable=1,scrollbars=1,toolbar=0,status=0";
    }
    $(this).bind ('click', function () {
      var ContextWindow = window.open (url, title, options);
      ContextWindow.focus();
      return false;
    });
  });
}

/*
if (window.attachEvent) {
  window.attachEvent("onload",setListeners);
}

function setListeners() {
  inputList = document.getElementsByTagName("INPUT");
  for(i=0;i<inputList.length;i++) {
    inputList[i].attachEvent("onpropertychange",restoreStyles);
      inputList[i].style.backgroundColor = "";
  }
  selectList = document.getElementsByTagName("SELECT");
  for(i=0;i<selectList.length;i++) {
    selectList[i].attachEvent("onpropertychange",restoreStyles);
    selectList[i].style.backgroundColor = "";
  }
}

function restoreStyles(){
  if(event.srcElement.style.backgroundColor != "") {
    event.srcElement.style.backgroundColor = "";
  }
}
*/

function form_is_modified (oForm) {
  if (!oForm || typeof oForm == "undefined" || !oForm.elements || typeof oForm.elements == "undefined") {
    return false;
  }
  
  var el, opt, hasDefault, i = 0, j;
  while (el = oForm.elements[i++]) {
    switch (el.type) {
      case 'text' :
      case 'textarea' :
      case 'hidden' :
        if (!/^\s*$/.test(el.value) && el.value != el.defaultValue) {  //verify aginst the default value
          return true;
        };
        break;
      case 'checkbox' :
      case 'radio' :
        if (el.checked != el.defaultChecked) {
          return true;
        };
        break;
      case 'select-one' :
      case 'select-multiple' :
        j = 0, hasDefault = false;
        while (opt = el.options[j++])
        if (opt.defaultSelected) hasDefault = true;
        j = hasDefault ? 0 : 1;
        while (opt = el.options[j++]) 
          if (opt.selected != opt.defaultSelected) {
            return true;
          } 
        break;
    }
  }
  return false;
}

function on_unload_dirty_form_check () {
  if (submitFlag != true) {
    if ($('#edit-page').val() == "basic" || $('#edit-page').val() == "contact") {
      if (location.pathname == "/mysbx-profile/my-profile/basic" || location.pathname == "/mysbx-profile/my-profile/contact") {
        var theForm = document.getElementById("mysbx-profile-form-loader");
        if (form_is_modified(theForm)) {
          if (confirm("Would you like to save the changes you've made to this page?")) {
            $("#mysbx-profile-form-loader").ajaxSubmit();
            return false;
          }
        }
      }
      else {
        theForm = document.getElementById("mysbx-company-profile-form");
        if (form_is_modified(theForm)) {
          if (confirm("Would you like to save the changes you've made to this page?")) {
            $("#mysbx-company-profile-form").ajaxSubmit();
            return false;
          }
        }
      }
    }
  
    if ($('#edit-page').val() == "exp" || $('#edit-page').val() == "edu") {
      var theForm = document.getElementById("mysbx-profile-form-loader");
      if (form_is_modified(theForm)) 
        if (confirm("Would you like to save the changes you've made to this page?")) 
          $("#mysbx-profile-form-loader").ajaxSubmit();
      return false;
    }
  
    if ($('#edit-page').val() == "cap" || $("#edit-page").val() == "cap/sc" || $('#edit-page').val() == "emp") {
      var theForm = document.getElementById("mysbx-company-profile-form");
      if (form_is_modified(theForm)) 
        if (confirm("Would you like to save the changes you've made to this page?")) 
          $("#mysbx-company-profile-form").ajaxSubmit();
      return false;
    }
  
    if (location.pathname == "/exchange/opportunity-exchange/post" || $('#edit-page').val() == "opprutinity-post") {
      var theForm = document.getElementById("node-form");
      if (form_is_modified(theForm)) 
        if (confirm("Would you like to save the changes you've made to this page?")) 
          $("#node-form").ajaxSubmit();
      return false;
    }
  
    if (location.pathname == "/exchange/resource-exchange/post" || location.pathname == "/work/knowledge-library-post" || location.pathname == "/node/add/resource-exchange" || $("#edit-resource-exchange-node-form").val() == "resource_exchange_node_form") {
      var theForm = document.getElementById("node-form");
      if (form_is_modified(theForm)) 
        if (confirm("Would you like to save the changes you've made to this page?")) 
          $("#node-form").ajaxSubmit();
      return false;
    }
  }
  else {
    oForm = $('<form id="no-name" style="display:none"><input type="hidden" value="nochange" /></form>');
  }
}

/**
  @author jschleiden
  *simplified menu hovers*
*/

function initFormHelp () { 
  $('form div.form-item .description').hover(
    function () {
      $(this).addClass("active");
    },
    function () {
      $(this).removeClass("active");
    }
  );
}

function initMenus () {
  $('#nav li').hover( 
    function () { 
      $(this).addClass("sfhover"); 
    }, 
    function () { 
      $(this).removeClass("sfhover"); 
    } 
  );
}

function sbx_fix_non_square_image_size () {
  imgs = $('img.avatar');
  jQuery.each (imgs, function (i, val) {
    img = $(this);

    naturalWidth = parseInt ($(this).attr ('sbximg-width'));  //this.naturalWidth;
    naturalHeight = parseInt ($(this).attr ('sbximg-height'));  //this.naturalHeight;

    css_width = this.width; //img.css ('width');
    css_height = this.height; //img.css ('height');

    if ((isNaN (naturalWidth) || isNaN (naturalHeight) || isNaN (css_width || isNaN (css_height)))) {
      return;
    }
    if (naturalWidth == naturalHeight) {
      return;
    }
    if (naturalWidth==0 || naturalHeight==0) {
      return;
    }
    if (css_width != css_height) {
      return;
    }

    if (css_width==0 || css_height==0) {
      return;
    }
    
    if (naturalWidth > naturalHeight) {
      scaled_height = naturalHeight*css_width/naturalWidth;
      img.css ('height', scaled_height + 'px');
    }
    else {
      scaled_width = naturalWidth*css_width/naturalHeight;
      img.css ('width', scaled_width + 'px');
    }
  });
}

$(document).ready (function () {
  $("a.sbx-dlink").click (function () {
    var anchor = $(this);
    var base_href = anchor.attr ('base_href');
    var href = anchor.attr ('href');
    if (!base_href) {
      base_href = href;
      anchor.attr ('base_href', base_href);
    }
    var dlink_id = anchor.attr ('sbxdlink_id');
    var input_selector = ':input[sbxdlink_id="' + dlink_id + '"]';
    var input_list = $(input_selector);
    var params = false;
    input_list.each (function () {
      var input_field = $(this);
      var pname = input_field.attr ('sbxdlink_pname');
      var pval = input_field.val ();
      var nv_pair = pname + '!' + pval;
      if (params == false) {
        params = nv_pair;
      }
      else {
        params += (';' + nv_pair);
      }
    });
    var param_href = base_href + params;
    anchor.attr ('href', param_href);
  });

  $(".btnLogout").click(function()
  {   
    var is_user_linked = 0;
    var iq_server = "";
    $.ajax({
        url: '/getuserlinked',
        type: 'POST',
        async: false,
        success: function(data){
         var current_path=window.location.pathname;
         var strArray =  data.split(',');
          if (strArray[0] == 1 || (strArray[2] == 1 && current_path == '/home')) {
            is_user_linked=1;
          }
          iq_server=strArray[1];
          logged_in_delegate=strArray[4];
        },
        error: function(xmlhttp){
          alert('An HTTP error ' + xmlhttp.status + ' occured.\n');
        }
      });
      if (is_user_linked == 1 && logged_in_delegate == 0)
      {
             location.replace("http://"+iq_server+"?userLogout=1");
             return false;
      }
  }
  );
});



/* Mega Menu, User Drop Down, User Rights Delegation Menu */


jQuery(document).ready(function() {
        function megaHoverOver(){jQuery(this).find('.sub').stop().fadeTo('fast', 1).show();}
        function megaHoverOut(){jQuery(this).find('.sub').stop().fadeTo('fast', 0, function() {jQuery(this).hide();});}

        var config = {
                 sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)
                 interval: 100, // number = milliseconds for onMouseOver polling interval
                 over: megaHoverOver, // function = onMouseOver callback (REQUIRED)
                 timeout: 300, // number = milliseconds delay before onMouseOut
                 out: megaHoverOut // function = onMouseOut callback (REQUIRED)
        };
        jQuery("ul#megaMenu li").hoverIntent(config);

        function showAccountMenu(){jQuery("#accountInfo ul li .sub").stop().fadeTo('fast', 1).show();jQuery('#accountInfo').addClass("accountMenuActive");}
        function hideAccountMenu(){jQuery("#accountInfo ul li .sub").stop().fadeTo('fast', 0).hide();jQuery('#accountInfo').removeClass("accountMenuActive");}

        var accountConfig = {
                 sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)
                 interval: 100, // number = milliseconds for onMouseOver polling interval
                 over: function(){}, // function = onMouseOver callback (REQUIRED)
                 timeout: 300, // number = milliseconds delay before onMouseOut
                 out: hideAccountMenu // function = onMouseOut callback (REQUIRED)
        };
        jQuery("#accountInfo ul li").hoverIntent(accountConfig);

        jQuery("#accountInfo").bind("click",function(){showAccountMenu(this);});


        function showDelegateMenu(){
          delegators = get_delegators();          
          markup = "<strong>A Delegate Account</strong><br />";
          for (delegate_list in delegators.delegators) {
             spanclass = "";
             if (delegators.delegators[delegate_list].current > 0)
               spanclass = " class='active' ";
             markup += "<span " + spanclass + ">" + delegators.delegators[delegate_list].name + " - ";
             if (delegators.delegators[delegate_list].current == 0)
               markup += "<a href='/user/delegate/switch/" + delegators.delegators[delegate_list].linkcode + "'>Switch to this Account</a><br />";
             else { 
               markup += "You are logged into this account";
               $("#delegateInfo ul li .sub .my-account span.active").removeClass("active");
             }
             markup += "</span>";
          }
          $('div.delegate-accounts').html(markup);
          jQuery("#delegateInfo ul li .sub").stop().fadeTo('fast', 1).show();
          jQuery('#delegateInfo').addClass("delegateMenuActive"); 
        }

        function hideDelegateMenu(){jQuery("#delegateInfo ul li .sub").stop().fadeTo('fast', 0).hide();jQuery('#delegateInfo').removeClass("delegateMenuActive");}

        var delegateConfig = {
                 sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)
                 interval: 100, // number = milliseconds for onMouseOver polling interval
                 over: function(){}, // function = onMouseOver callback (REQUIRED)
                 timeout: 300, // number = milliseconds delay before onMouseOut
                 out: hideDelegateMenu // function = onMouseOut callback (REQUIRED)
        };
        jQuery("#delegateInfo ul li").hoverIntent(delegateConfig);
        jQuery("#delegateInfo").bind("click",function(){showDelegateMenu(this);});
});




