﻿/// needed for jQuery Intellisense to work /Jonas
/// <reference path="jquery-1.3.2.js" />

$.ns('AEC');

window.debug = (document.location.hostname === "gullbergs.se" || document.location.hostname === "localhost");

  

$.fn.findOnce = function(selector, name)
{
	if(!name) name = "{BINDONCE " + selector + " }";
	var ems = $(this).find(selector);
	var result = [];
	for(var i=0, mi=ems.length; i<mi; ++i)
	{
		var em = $(ems[i]);
		if(!em.data(name))
		{
			result.push(em);
			em.data(name, true);
		}
	}
	return $(result);
}; 

AEC.Global = {
    init : function() {
      if ($.browser.msie) {
        jQuery("body").addClass("ie-" + $.browser.version.split('.')[0]);
      }

      // Global error handling
      $().ajaxError(function(event, xhr, options) {
        if (options.error || options.ignoreErrors) {
          // If the XHR caller has specified an error callback or set ignoreErrors = true then do nothing
          return;
        }
        
        if(xhr.readyState == 0 || xhr.status == 0) {
              // Not really an error, user navigated away from a page while an ajax request is ongoing
              return;  
        }
                 
        var msg;
        if (xhr.status === 500) {
          msg = xhr.responseText;
        } else {
          msg = debug ? xhr.responseText : rm.get('Error_GENERAL_ERROR');
        }
        
        var buttons = {};
        buttons[rm.get('Common_Close')] = function() {
          $(this).dialog("close"); 
        };
        
        AEC.Dialog.show({
          title : rm.get('Error_SHORT'),
          message : msg,
          buttons : buttons       
        });
      });
      
      // Google analytics
      var gaJsHost = ("https:" == document.location.protocol) ? "https://ssl.google-analytics.com/ga.js" : 
                                                                "http://www.google-analytics.com/ga.js";
      $.getScript(gaJsHost, function() {
        try {
            var pageTracker = _gat._getTracker("UA-6228365-2");
            pageTracker._trackPageview();

            var pageTracker2 = _gat._getTracker("UA-12443821-1");
            pageTracker2._trackPageview();
          } catch (err) { }
      }, true);
      
      if ($.fn.checkbox && (!$.browser.msie || $.browser.version != "6.0")) {
	      $(".prettyCheckbox, .prettyRadio").checkbox();
	    }
	    
	    // Z-index issue with IE ver. <= 7
      if ($.browser.msie) {
	      $(function() {
	        var zIndexNumber = 1000;
	        $('div').each(function() {
		        $(this).css('zIndex', zIndexNumber);
		        zIndexNumber -= 10;
	        });
        });
      }
      $.fn.fancybox.build();
    }
};

$(document).ready(AEC.Global.init);

function thumbsPreload(target_items) {
  $(target_items).each(function(i) {
    jQuery("<img>").attr("src", $(this).attr('id'));
  });
}

// OBSOLETE: Use AEC.Dialog.show()
showMessageDialog = AEC.Dialog.show;

// OBSOLETE: Use AEC.Dialog.showError()
showErrorDialog = AEC.Dialog.showError;

// OBSOLETE: Use AEC.Dialog.showProgress()
showProgressDialog = AEC.Dialog.showProgress;

// OBSOLETE: Use AEC.Dialog.hide()
// handles dialog hiding for all dialogs (message, error, progress and info)
hideMessageDialog = AEC.Dialog.hide;

// OBSOLETE: generic method to post an update with AJAX and handle the response showing dialogs
function postUpdate(frm, posturl, onSuccess) {
  AEC.Dialog.showProgress({ message : 'Don\'t use postUpdate, for form submission through AJAX use the AjaxForm plugin (jquery.form.js)' });
  $.ajax({
    url: posturl,
    type: "POST",
    data: frm,
    success: function(msg) {
      AEC.Dialog.hide();
      if (msg != "ok") {
        AEC.Dialog.showError(msg);
      }
      else {
        if (typeof onSuccess != undefined) {
          if (onSuccess.constructor == String) {
            AEC.Dialog.show({ message: onSuccess, duration: 2000 });
          }
          else if (onSuccess.constructor == Function) {
            onSuccess();
          }
        }
      }
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
      AEC.Dialog.showError(rm.get("Shared_Error_ContactSupport"));
    }
  });
}

function log(msg, url, line) {
  var img = new Image();
  img.src = "/Commerce/Logjserror/?file=" + encodeURIComponent(url) + "&rownumber=" + encodeURIComponent(line) + "&error=" + encodeURIComponent(msg);
}

// Disabled since there is no logging functionality implemented yet
//window.onerror = function(msg, url, line) {
//  if (!debug) {
//    try {
//      log(msg, url, line);
//    } 
//    catch (e) {
//    }
//    finally {
//      return true;
//    }
//  } else {
//    return false;
//  }
//};

AEC.Utilities = {
  isEnterKeyEvent : function(e) {
    return (e.which && e.which == 13) || (e.keyCode && e.keyCode == 13);
  }
};


Function.prototype.bind = Function.prototype.bind || function() {
  var method = this, target = arguments[0], args = [];
  for(var i=1, mi=arguments.length; i<mi; ++i) args[i-1] = arguments[i];
  return function() { return method.apply(target, args); };
};

