var errors = [];
var shitBrowser = false;		// flag for IE < 7

$(document).ready(function(){
	// flag to say if the browser is IE < 7, and hence has to have degraded animation (bounced images disappear for example)
	if ($.browser.msie && $.browser.version.substr(0,1)<7) shitBrowser = true;
	
	// add the expando for the privacy policy section
	$('#privacy-policy').privacySection();
	
	function megaHoverOver(){
		$(this).find(".mm").stop().hide('fast', 1).show();
			
		//Calculate width of all ul's
		(function($) { 
			jQuery.fn.calcSubWidth = function() {
				rowWidth = 0;
				rowHeight = 0;
				numCols = 0;
				//Calculate row
				$(this).find("ul").each(function() {					
					rowWidth += $(this).width(); 
					if ($(this).height() > rowHeight){
						rowHeight = $(this).height();
					}
					numCols++;
				});	
			};
		})(jQuery); 
		
		if ( $(this).find(".row").length > 0 ) { //If row exists...
			var biggestRow = 0;	
			//Calculate each row
			$(this).find(".row").each(function() {							   
				$(this).calcSubWidth();
				//Find biggest row
				if(rowWidth > biggestRow) {
					biggestRow = rowWidth;
				}
			});
			//Set width
			$(this).find(".menu-bottom-center").css({'width' : rowWidth});
			$(this).find(".menu-top-center").css({'width' :biggestRow});
			$(this).find(".mm").css({'width' :biggestRow + 41});
			$(this).find(".row:last").css({'margin':'0'});
			
		} else { //If row does not exist...
			
			$(this).calcSubWidth();
			//Set Width
			$(this).find(".menu-middle-left").css({'height' : rowHeight + 10});
			$(this).find(".menu-middle-right").css({'height' : rowHeight + 10});
			// console.log($(this).attr('class'));
			if(($(this).attr('class').match('mm-magazines-from-abroad'))){
				$(this).find(".menu-bottom-center").css({'width' : 270});
				$(this).find(".menu-top-center").css({'width' : 270});
				$(this).find(".menu-middle-center").css({'width' : 250});
				$(this).find(".menu-top-row-2-center").css({'width' : 270});
				$(this).find(".mm").css({'width' : 250 + 61});
			}
			else{
				$(this).find(".menu-bottom-center").css({'width' : rowWidth + 20});
				$(this).find(".menu-top-center").css({'width' : rowWidth + 20});
				$(this).find(".menu-top-row-2-center").css({'width' : rowWidth + 20});
				$(this).find(".mm").css({'width' : rowWidth + 61});
			}
			/* If the menu width is greater than a certain dimension center it on the screen */
			if($(this).attr('class').match('mm-free-brochures')){	
			}
			else if (rowWidth > 600){
				$(this).find(".mm").css({'left' : '50%', 'margin-left' : (Math.round(rowWidth/-2))});
				position = $(this).offset();
				menuleft = $(this).find(".mm").offset();
				topPos = (-1 * menuleft.top) + position.top - 4;	
				leftPos = (position.left - menuleft.left) - 5;
				$(this).find(".tab").css({'left': leftPos});
			}
			
			else{
				$(this).find(".mm").css({'margin-left' : -3});				
			}
			
		}
	}
	
	function megaHoverOut(){ 
	  $(this).find(".mm").stop().hide('fast', 0, function() {
		  $(this).hide(); 
	  });
	}
 
 
	var config = {    
		 sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)    
		 interval: 50, // number = milliseconds for onMouseOver polling interval    
		 over: megaHoverOver, // function = onMouseOver callback (REQUIRED)    
		 timeout: 100, // number = milliseconds delay before onMouseOut    
		 out: megaHoverOut // function = onMouseOut callback (REQUIRED)    
	};
 
	//$("ul.topnav li .sub").css({'opacity':'0'});
	try{
		if (! shitBrowser){
			$("ul#header-navigation li").bgiframe().hoverIntent(config);
		}
	}
	catch (e){
				
	}
});


function fnShowCheckoutErrrorMessage(_msg){
	var target = mode = '';
	var oElem;
	var pos = eWidth = mWidth = left = top = 0 + "px";
	if (arguments.length > 1){
		target = arguments[1];
	}
	
	if (arguments.length > 2){
		mode = arguments[2];
	}
	
	
	if ((target != '')){
		// get the parent element of target
		oParent = $('#' + target).parent();
		// append the message to the parent
		$('<div id="' + target + '_fielderror" class="errornotificationdiv"><p>' + _msg + '</p></div>').appendTo(oParent).css({
			width: parseInt($('#' + target).css('width')) + 6
		}).fadeIn().effect("highlight", {color: '#ff0000'}, 1000);
		errors.push(target + '_fielderror');
	}	
	
}

function fnShowError(_msg){
   		
	var target = mode = '';
	var oElem;
	var pos = eWidth = mWidth = left = top = 0 + "px";
	var toolTipStart = '<div class="error-tooltip"><div class="tooltip-top"></div><div class="tooltip-body"><div class="tooltip-pointer"><img src="./_assets/shared/images/tooltip/pointer.png" width="23" height="24" border="0" alt="" /></div><div class="tooltip-content"><p>';
	var toolTipEnd = '</p></div></div><div class="tooltip-bottom"></div></div>';
	var toolTipHTML = '<div class="error-tool-tip"><table width="293" cellpadding="0" cellspacing="0" border="0"><tbody><tr><td class="left-col-top" align="right" width="16"><img src="/_assets/shared/images/errors/tool-tip/top-left.png" width="8" height="8" border="0" /></td><td class="middle-col-top" align="right" width="269"><img src="/_assets/shared/images/errors/tool-tip/blank.gif" width="269" height="8" border="0" /></td><td class="right-col-top" align="left"><img src="/_assets/shared/images/errors/tool-tip/top-right.png" width="8" height="8" border="0" /></td></tr><tr><td valign="top" class="left-col-middle" width="16" height="17"><img src="/_assets/shared/images/errors/tool-tip/pointer.png" width="16" height="17" border="0"></td><td valign="top" class="middle-col-middle"></td><td valign="top" class="right-col-middle"><img src="/_assets/shared/images/blank.gif" width="8" height="1" border="0"></td></tr><tr><td class="left-col-bottom" align="right"><img src="/_assets/shared/images/errors/tool-tip/bottom-left.png" width="8" height="8" border="0" /></td><td class="middle-col-bottom" align="right" width="269"><img src="/_assets/shared/images/errors/tool-tip/bottom-middle.png" width="269" height="8" border="0" /></td><td class="right-col-bottom" align="left"><img src="/_assets/shared/images/errors/tool-tip/bottom-right.png" width="8" height="8" border="0" /></td></tr></tbody></table></div>';
	var toolTipNotificationHTML = '<div class="error-tool-tip-notification"><table width="293" cellpadding="0" cellspacing="0" border="0"><tbody><tr><td class="left-col-top" align="right" width="8"><img src="/_assets/shared/images/errors/tool-tip/top-left.png" width="8" height="8" border="0" /></td><td class="middle-col-top" align="right" width="269"><img src="/_assets/shared/images/errors/tool-tip/blank.gif" width="269" height="8" border="0" /></td><td class="right-col-top" align="left"><img src="/_assets/shared/images/errors/tool-tip/top-right.png" width="8" height="8" border="0" /></td></tr><tr><td valign="top" class="left-col-middle" width="8"><img src="/_assets/shared/images/blank.gif" width="8" height="1" border="0"></td><td valign="top" class="middle-col-middle"></td><td valign="top" class="right-col-middle"><img src="/_assets/shared/images/blank.gif" width="8" height="1" border="0"></td></tr><tr><td class="left-col-bottom" align="right" valign="top"><img src="/_assets/shared/images/errors/tool-tip/bottom-left.png" width="8" height="8" border="0" /></td><td class="middle-col-bottom" align="left"><img src="/_assets/shared/images/errors/tool-tip/pointer-down.png" width="17" height="16" border="0" /></td><td class="right-col-bottom" align="left" valign="top"><img src="/_assets/shared/images/errors/tool-tip/bottom-right.png" width="8" height="8" border="0" /></td></tr></tbody></table></div>';
	if (arguments.length > 1){
		target = arguments[1];
	}
	
	if (arguments.length > 2){
		mode = arguments[2];
	}
	
	
	if ((target != '')){
			
		switch (mode){
			
			case 'field':
					// check if target has the word terms in it use the parent element as the target
					/*if ((target.indexOf('terms') != -1) && (target != 'isubscribe_terms')){
						parentId = $('#' + target).parent().attr('id');
						if (parentId.length == 0){
							parentId = target + "_parent";
							$('#' + target).parent().attr('id', parentId);								
						}
						target = parentId;
					}*/
					
			        
			        // special case
			        if (target == 'isubscribe_terms'){
			        	pos = $('#' + target).offset();    
					    eWidth = $('#' + target).outerWidth();
						mWidth = 200;
				        left = (pos.left + eWidth + 45) + "px";
				        top = (pos.top - 1) + "px";
			        	refDimensions = $('#other').offset();
			        	$('#termsToolTip-container').clone().attr('id', target + '_fielderror').addClass('termsToolTip').css({
							position: 'absolute',
							zIndex: 2,
							left: (refDimensions.left + $('#other').width() + 2) ,
							top: pos.top - 10
						}).appendTo('body').fadeIn();
						
			        	$('.tool-tip-close a').bind('click', function(event){
			    			event.preventDefault();
			    			$('#isubscribe_terms_fielderror').fadeOut().remove();
			    		});
			        }
			        else if(target.indexOf('terms') != -1){
			        	try{
							// notifications are shown as a full div after target;
							$('#' + target).before($(toolTipNotificationHTML).attr('id', target + '_fielderror'));
							$('div#' + target + '_fielderror td.middle-col-middle').html(_msg).fadeIn();
							
								
						}
						catch(e){}
						errors.push(target + '_fielderror');
			        	
			        }
			        else{
			        	
			        	
			        	// clone the base element
			        	// only show if the target is visible
			        	if ($('#' + target).is(":visible")){
			        		// add extra padding to the bottom of the element
							//$('#' + target).addClass('error-field-js');
			        		pos = $('#' + target).offset();    
						    eWidth = $('#' + target).outerWidth();
						    eHeight = $('#' + target).outerHeight();
							mWidth = 200;
					        left = (pos.left + eWidth + 75) + "px";
					        top = (pos.top - 10) + "px";
					        
							$(toolTipHTML).attr('id', target + '_fielderror').css({
								position: 'absolute',
								zIndex: 2,
								left: left,
								top: top
							}).appendTo('body').fadeIn(); //.effect("highlight", {color: '#d6c7bf'}, 1000);
							$('div#' + target + '_fielderror td.middle-col-middle').html(_msg);
							// bind a handler to the target, if focus then hide error
							$('#' + target).bind('focus', function(event){
								$('#' + target + '_fielderror').fadeOut().remove();
								$('#' + target).removeClass('error-field-js');
							});
							
			        	}
			        }

					errors.push(target + '_fielderror');
				break;
			case 'prebuilt':
				
				pos = $('#' + target).offset();    
			    eWidth = $('#' + target).outerWidth();
				var mWidth = 200;
		        var left = (pos.left + eWidth + 2) + "px";
		        var top = (pos.top - 1) + "px";
		        
	        	refDimensions = $('.checkout-form-content-payment-cc').offset();
	        	$('#' + target + '_fielderror').addClass('termsToolTip').css({
					position: 'absolute',
					zIndex: 2,
					left: (refDimensions.left + $('.checkout-form-content-payment-cc').width() + 2) ,
					top: pos.top - 10
				}).appendTo('body').fadeIn();
				
	        	$('.tool-tip-close a').bind('click', function(event){
	    			event.preventDefault();
	    			$('#' + target + '_fielderror').fadeOut().remove();
	    		});

				errors.push(target + '_fielderror');
				break;
			case 'checkout-popup':
				
				break;
			case 'notification':
					// notifications are shown as a full div after target;
					sError = '<div id="notification-' + target + '" class="notification" style="display: none">' + _msg + '<div class="clear"></div></div>';
					$('#' + target).after(sError);
					$('#notification-' + target).fadeIn().effect("highlight", {color: '#d6c7bf'}, 3000);
					errors.push('notification-' + target);
					setTimeout("fnHideErrors()", 6000);
				break;
			case 'error-notification':
				
				try{
					// notifications are shown as a full div after target;
					$('#' + target).after($(toolTipNotificationHTML).attr('id', target + '_fielderror'));
					$('div#' + target + '_fielderror td.middle-col-middle').html(_msg).fadeIn();
					
						
				}
				catch(e){}
				errors.push(target + '_fielderror');
					
				break;
			
		}
		
	}
}

function fnHideErrors(){
	
	$.each(errors, function(){
		$('#' + this).fadeOut().remove();
	});
	$('input').removeClass('error-field-js');
	errors = [];
}

/* basic jQuery expando for category view */
jQuery.fn.extend({
	expando: function() {
		var dst = $('ul,ol',$(this));
		
		$('.expando-openCloseLink a',$(this)).bind('click',function(){
			
			if($(this).html() == 'see all') {
				$(dst).show('slow');
				$(this).html('hide all');
			} else
			{
				$(dst).hide('slow');
				$(this).html('see all');
			}
			
			return false;
		});
	},
	
	privacySection: function() {
		// listener for anchor click
		$('li>a',$(this)).bind('click',function(){
			if($('div',$(this).parent()).is(':hidden')) {
				$('div',$(this).parent()).show('slow');
			} else
			{
				$('div',$(this).parent()).hide('slow');
			}
			
			return false;
		});
	}
});

/**
 * jQuery.query - Query String Modification and Creation for jQuery
 * Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com)
 * Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
 * Date: 2009/8/13
 *
 * @author Blair Mitchelmore
 * @version 2.1.7
 *
 **/
new function(settings) { 
  // Various Settings
  var $separator = settings.separator || '&';
  var $spaces = settings.spaces === false ? false : true;
  var $suffix = settings.suffix === false ? '' : '[]';
  var $prefix = settings.prefix === false ? false : true;
  var $hash = $prefix ? settings.hash === true ? "#" : "?" : "";
  var $numbers = settings.numbers === false ? false : true;
  
  jQuery.query = new function() {
    var is = function(o, t) {
      return o != undefined && o !== null && (!!t ? o.constructor == t : true);
    };
    var parse = function(path) {
      var m, rx = /\[([^[]*)\]/g, match = /^([^[]+)(\[.*\])?$/.exec(path), base = match[1], tokens = [];
      while (m = rx.exec(match[2])) tokens.push(m[1]);
      return [base, tokens];
    };
    var set = function(target, tokens, value) {
      var o, token = tokens.shift();
      if (typeof target != 'object') target = null;
      if (token === "") {
        if (!target) target = [];
        if (is(target, Array)) {
          target.push(tokens.length == 0 ? value : set(null, tokens.slice(0), value));
        } else if (is(target, Object)) {
          var i = 0;
          while (target[i++] != null);
          target[--i] = tokens.length == 0 ? value : set(target[i], tokens.slice(0), value);
        } else {
          target = [];
          target.push(tokens.length == 0 ? value : set(null, tokens.slice(0), value));
        }
      } else if (token && token.match(/^\s*[0-9]+\s*$/)) {
        var index = parseInt(token, 10);
        if (!target) target = [];
        target[index] = tokens.length == 0 ? value : set(target[index], tokens.slice(0), value);
      } else if (token) {
        var index = token.replace(/^\s*|\s*$/g, "");
        if (!target) target = {};
        if (is(target, Array)) {
          var temp = {};
          for (var i = 0; i < target.length; ++i) {
            temp[i] = target[i];
          }
          target = temp;
        }
        target[index] = tokens.length == 0 ? value : set(target[index], tokens.slice(0), value);
      } else {
        return value;
      }
      return target;
    };
    
    var queryObject = function(a) {
      var self = this;
      self.keys = {};
      
      if (a.queryObject) {
        jQuery.each(a.get(), function(key, val) {
          self.SET(key, val);
        });
      } else {
        jQuery.each(arguments, function() {
          var q = "" + this;
          q = q.replace(/^[?#]/,''); // remove any leading ? || #
          q = q.replace(/[;&]$/,''); // remove any trailing & || ;
          if ($spaces) q = q.replace(/[+]/g,' '); // replace +'s with spaces
          
          jQuery.each(q.split(/[&;]/), function(){
            var key = decodeURIComponent(this.split('=')[0] || "");
            var val = decodeURIComponent(this.split('=')[1] || "");
            
            if (!key) return;
            
            if ($numbers) {
              if (/^[+-]?[0-9]+\.[0-9]*$/.test(val)) // simple float regex
                val = parseFloat(val);
              else if (/^[+-]?[0-9]+$/.test(val)) // simple int regex
                val = parseInt(val, 10);
            }
            
            val = (!val && val !== 0) ? true : val;
            
            if (val !== false && val !== true && typeof val != 'number')
              val = val;
            
            self.SET(key, val);
          });
        });
      }
      return self;
    };
    
    queryObject.prototype = {
      queryObject: true,
      has: function(key, type) {
        var value = this.get(key);
        return is(value, type);
      },
      GET: function(key) {
        if (!is(key)) return this.keys;
        var parsed = parse(key), base = parsed[0], tokens = parsed[1];
        var target = this.keys[base];
        while (target != null && tokens.length != 0) {
          target = target[tokens.shift()];
        }
        return typeof target == 'number' ? target : target || "";
      },
      get: function(key) {
        var target = this.GET(key);
        if (is(target, Object))
          return jQuery.extend(true, {}, target);
        else if (is(target, Array))
          return target.slice(0);
        return target;
      },
      SET: function(key, val) {
        var value = !is(val) ? null : val;
        var parsed = parse(key), base = parsed[0], tokens = parsed[1];
        var target = this.keys[base];
        this.keys[base] = set(target, tokens.slice(0), value);
        return this;
      },
      set: function(key, val) {
        return this.copy().SET(key, val);
      },
      REMOVE: function(key) {
        return this.SET(key, null).COMPACT();
      },
      remove: function(key) {
        return this.copy().REMOVE(key);
      },
      EMPTY: function() {
        var self = this;
        jQuery.each(self.keys, function(key, value) {
          delete self.keys[key];
        });
        return self;
      },
      load: function(url) {
        var hash = url.replace(/^.*?[#](.+?)(?:\?.+)?$/, "$1");
        var search = url.replace(/^.*?[?](.+?)(?:#.+)?$/, "$1");
        return new queryObject(url.length == search.length ? '' : search, url.length == hash.length ? '' : hash);
      },
      empty: function() {
        return this.copy().EMPTY();
      },
      copy: function() {
        return new queryObject(this);
      },
      COMPACT: function() {
        function build(orig) {
          var obj = typeof orig == "object" ? is(orig, Array) ? [] : {} : orig;
          if (typeof orig == 'object') {
            function add(o, key, value) {
              if (is(o, Array))
                o.push(value);
              else
                o[key] = value;
            }
            jQuery.each(orig, function(key, value) {
              if (!is(value)) return true;
              add(obj, key, build(value));
            });
          }
          return obj;
        }
        this.keys = build(this.keys);
        return this;
      },
      compact: function() {
        return this.copy().COMPACT();
      },
      toString: function() {
        var i = 0, queryString = [], chunks = [], self = this;
        var encode = function(str) {
          str = str + "";
          if ($spaces) str = str.replace(/ /g, "+");
          return encodeURIComponent(str);
        };
        var addFields = function(arr, key, value) {
          if (!is(value) || value === false) return;
          var o = [encode(key)];
          if (value !== true) {
            o.push("=");
            o.push(encode(value));
          }
          arr.push(o.join(""));
        };
        var build = function(obj, base) {
          var newKey = function(key) {
            return !base || base == "" ? [key].join("") : [base, "[", key, "]"].join("");
          };
          jQuery.each(obj, function(key, value) {
            if (typeof value == 'object') 
              build(value, newKey(key));
            else
              addFields(chunks, newKey(key), value);
          });
        };
        
        build(this.keys);
        
        if (chunks.length > 0) queryString.push($hash);
        queryString.push(chunks.join($separator));
        
        return queryString.join("");
      }
    };
    
    return new queryObject(location.search, location.hash);
  };
}(jQuery.query || {}); // Pass in jQuery.query as settings object


/**
 * Fuck-up prevention; checks to see if the console exists before posting to it, so that console.log messages that are accidentally left in do not break a page when run live
 * Called "trace" as I have been doing a lot of AS3 today and I keep typing it anyway
 * @param message
 * @return void
 */
function trace(message) {
    if(typeof(console) != 'undefined' && typeof(console.log) == 'function') {
	console.log(message);
    }
}
