var MegaMenu = {
  megaMenuShowWait: 500,
  megaMenuHideWait: 500,
  megaMenuShowTO: null,
  megaMenuHideTO: null,

  highlightLink: function(e) {
    clearTimeout(MegaMenu.megaMenuShowTO);
    $('.MegaMenuLink, .mainCatLink').removeClass('active');
    $(this).addClass('active');
    $('.MegaMenuContent:visible').hide();
  },

  highlightSubLink: function(e) {
    $(this).addClass('active');
  },

  unhighlightLink:  function(e) {
    clearTimeout(MegaMenu.megaMenuShowTO);
    $(this).removeClass('active');
  },

  showMegaMenu: function(e) {
    clearTimeout(MegaMenu.megaMenuShowTO);
    $('.MegaMenuLink, .mainCatLink').removeClass('active');
    $(this).addClass('active');
    $('.MegaMenuContent:visible').hide();

    var id = $(this).attr('rel');
    var contentSel = '#MegaMenuContent_'+id;
    var leftPos = $(this).position().left + $(this).parent().width() - 3;
    var topPos = $(this).position().top;
    var width = $(contentSel).width();
    var height = $(contentSel).height();
    $(contentSel).css({ left: leftPos+'px', top:	topPos+'px' });
    if ($('.MegaMenuContent:visible').length > 0) {
      $('.MegaMenuContent').hide();
      $(contentSel).show();
      $('.MegaMenuLink[rel="'+id+'"]').addClass('active');
    } else {
      $('.MegaMenuContent').hide();
      clearTimeout(MegaMenu.megaMenuShowTO);
      MegaMenu.megaMenuShowTO = setTimeout(function() {
        $(contentSel).show();
        $('.MegaMenuLink[rel="'+id+'"]').addClass('active');
      }, MegaMenu.megaMenuShowWait);
    }
  },

  hideMegaMenu: function(e) {
    var id = $(this).attr('rel');
    var contentSel = '#MegaMenuContent_'+id;
    clearTimeout(MegaMenu.megaMenuHideTO);
    MegaMenu.megaMenuHideTO = setTimeout(function() {
      $(contentSel).hide();
      $('.MegaMenuLink[rel="'+id+'"]').removeClass('active');
    }, MegaMenu.megaMenuHideWait);
  },

  cancelTimeout: function(e) {
    clearTimeout(MegaMenu.megaMenuHideTO);
  },

  resumeTimeout: function(e) {
    var contentSel = '#'+$(this).attr('id');
    var id = contentSel.replace('#MegaMenuContent_','');
    clearTimeout(MegaMenu.megaMenuHideTO);
    MegaMenu.megaMenuHideTO = setTimeout(function() {
      $(contentSel).hide();
      $('.MegaMenuLink[rel="'+id+'"]').removeClass('active');
    }, MegaMenu.megaMenuHideWait);
  },

  clickLink: function(e) {
    if (!$(e.target).is('a')) {
      var id = $(this).closest('.MegaMenuLink').attr('rel');
      var contentSel = '#MegaMenuContent_'+id;
      var leftPos = $(this).position().left + $(this).parent().width() - 3;
      var topPos = $(this).position().top;
      var width = $(contentSel).width();
      var height = $(contentSel).height();
      $(contentSel).css({ left: leftPos+'px', top:	topPos+'px' });
      clearTimeout(MegaMenu.megaMenuShowTO);
      $('.MegaMenuLink[rel="'+id+'"]').addClass('active');
      $(contentSel).show();
    }
  },

  clickOff: function(e) {
    var target = e.target;
    if (
      $(target).closest('.MegaMenuContent').length === 0 &&
      $(target).closest('.MegaMenuLink').length === 0 &&
      $(target).closest('.SubCatLink').length === 0
    ) {
      clearTimeout(MegaMenu.megaMenuShowTO);
      $('.MegaMenuLink,.mainCatLink,.SubCatLink').removeClass('active');
      $('.MegaMenuContent').hide();
    }
  },

  followLink: function(e) {
    var url = $(this).find('a').attr('href');
    if (url) {
      document.location = url;
    }
  },

  init: function() {
    $(".MegaMenuContent").bind('mouseenter', this.cancelTimeout).bind('mouseleave', this.resumeTimeout);
    $(".MegaMenuLink").bind('click', this.clickLink).bind('mouseenter', this.showMegaMenu).bind('mouseleave', this.hideMegaMenu);
    $('.mainCatLink, .SubCatLink').bind('click', this.followLink).bind('mouseleave', this.unhighlightLink);
    $(".mainCatLink").bind('mouseenter', this.highlightLink);
    $(".SubCatLink").bind('mouseenter', this.highlightSubLink);
    $(document).bind('click.MegaMenu', this.clickOff);
  }

};

if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, '');
  };
}

function number_format(number, decimals, dec_point, thousands_sep) {
    var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
    var d = dec_point === undefined ? "." : dec_point;
    var t = thousands_sep === undefined ? "," : thousands_sep, s = n < 0 ? "-" : "";
    var i = parseInt(n = Math.abs(+n || 0).toFixed(c), 10) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}

function parseAndAddClass(text,classToAdd) {
	var classExists = text.indexOf('class="') !== -1;
	var classes = '';
	var currentClasses;
	if (classExists) {
		currentClasses = text.substr(text.indexOf('class="')+('class="').length);
		currentClasses = currentClasses.substr(0,currentClasses.indexOf('"'));
	}
	classes = currentClasses + ' ' + classToAdd;
	if (classExists) {
		text = text.replace(/class=\".*?\"/g,'class="'+classes+'"');
	} else {
		text = text + ' class="'+classes+'"';
	}
	return text;
}

function tep_cool_button(text, link, tip, args, disabled) {
	if (typeof(text) == 'undefined') { text = 'Click Here'; }
	if (typeof(link) == 'undefined') { link = ""; }
	if (typeof(tip) == 'undefined') { tip = ''; }
	if (typeof(args) == 'undefined') { args = ''; }
	if (typeof(disabled) == 'undefined') { disabled = false; }
	var cmd = link;
	if (link.indexOf('http://') === 0 || link.indexOf('https://') === 0) {
		cmd = "document.location.href='"+link+"';";
		if (args.indexOf('target="_blank"') !== -1 || (args.indexOf("target='_blank'") !== -1)) {
			cmd = "window.open('"+link+"');";
		}
	}
	var extra_classes = '';
	if (args.indexOf('class="') !== -1) {
		extra_classes = args.substr(args.indexOf('class="')+('class="').length);
		extra_classes = extra_classes.substr(0,extra_classes.indexOf('"'));
		extra_classes = ' '+extra_classes;
	}
	return '<button class="coolButton '+extra_classes+'"'+(disabled ? ' disabled="disabled"' : '')+' title="'+tip+'" '+args+' onclick="'+cmd+'">'+text+'</button>';
}

function tep_cool_button_small(text, link, tip, args, disabled) {
	if (typeof(args) == 'undefined') { args = ''; }
	args = parseAndAddClass(args,'small');
	return tep_cool_button(text,link,tip,args,disabled);
}

function tep_cool_dropdown_button(text, cmd, tip, args, disabled) {
	if (typeof(text) == 'undefined') { text = 'Click Here'; }
	text = text + '<img class="dropdownarrow" src="images/ddn.png">&nbsp;';
	return tep_cool_button(text,cmd,tip,args,disabled);
}

function tep_cool_dropdown_button_small(text, cmd, tip, args, disabled) {
	if (typeof(args) == 'undefined') { args = ''; }
	args = parseAndAddClass(args,'small');
	return tep_cool_dropdown_button(text,cmd,tip,args,disabled);
}

function tep_cool_split_button(text, cmd, splitcmd, tip, args, disabled) {
	if (typeof(text) == 'undefined') { text = 'Click Here'; }
	if (typeof(cmd) == 'undefined') { cmd = "alert('No action defined.');"; }
	if (typeof(splitcmd) == 'undefined') { splitcmd = "alert('No split action defined.');"; }
	if (typeof(args) == 'undefined') { args = ''; }
	args1 = parseAndAddClass(args,'split');
	args2 = parseAndAddClass(args,'splitDropDown');
	return 	tep_cool_button(text,cmd,tip,args,disabled) +
					tep_cool_button('<img src="images/ddn.png">',splitcmd,tip,args,disabled);
}

function tep_cool_split_button_small(text, cmd, splitcmd, tip, args, disabled) {
	if (typeof(args) == 'undefined') { args = ''; }
	args = parseAndAddClass(args,'small');
	return tep_cool_split_button(text,cmd,splitcmd,tip,args,disabled);
}

function coolbutton_dropdown_menu_hide(mnu) {
	// Do any cleanup logic here...
	$(document).unbind('click');
	$(mnu).fadeOut('fast');
}

function coolbutton_dropdown_menu_position(btn, mnu) {
	// get size and location of the button
	var btnLeft = $(btn).offset().left;
	var btnID = $(btn).attr("id");
	var btnIndex = btnID.substr(btnID.length-1, 1);
	var btnTop = $(btn).offset().top + 5;
	var btnWidth = $(btn).width();
	var btnHeight = $(btn).height();

	// get document positions
	var docWidth = $(window).width();
	var ddWidth = $(mnu).width() + 2;

	// if we are falling off the right side of the page, move it left a bit
	if ((btnLeft + ddWidth) > docWidth) { btnLeft = (docWidth - ddWidth); }

	$(mnu).css("left", btnLeft);
	$(mnu).css("top", btnTop + btnHeight);
}

function coolbutton_dropdown_menu_show(btn, mnu) {
	coolbutton_dropdown_menu_position(btn, mnu);

	// show the dropdown
	$(mnu).fadeIn('fast', function() {
		// bind click to document for hiding
		$(document).click(function(e) {
			e.stopPropagation();
			coolbutton_dropdown_menu_hide(mnu);
		});
		$(window).resize(function(e) {
			coolbutton_dropdown_menu_hide(mnu);
		});

		$(mnu).click(function(e) { e.stopPropagation(); });
		$(mnu).find(".separator, .custom_item").click(function(e) { e.stopPropagation(); });
	});
}

function removeServiceOption(opt,pid,s,t) {
	var post_data = {
		action: 'remove_service_option',
		opt:		opt,
		pid:		pid,
		s:			s,
		t:			t
	};
	jQuery.ajax({url:'catalog_ajax.php',data:post_data,type:'POST',dataType:'json',success:function(json){
		if (json.status.code == 'OK') {
			document.location.reload(true);
		} else {
			alert(json.status.message);
		}
	}});
}

function addServiceOption(opt,pid,s,t) {
	var post_data = {
		action: 'add_service_option',
		opt:		opt,
		pid:		pid,
		s:			s,
		t:			t
	};
	jQuery.ajax({url:'catalog_ajax.php',data:post_data,type:'POST',dataType:'json',success:function(json){
		if (json.status.code == 'OK') {
			document.location.reload(true);
		} else {
			alert(json.status.message);
		}
	}});
}

function ajaxRecordError(e,p) {
  //e ===~ (string) error message
  //p ===~ (string) page occurred
  var post_data = {
    action: 'record_error',
    e: e,
    p: p
  };
  $.ajax({url:'catalog_ajax.php',data:post_data,type:'POST',dataType:'json'});
}

function createCookie(name,value,days) {
  var expires = '';
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		expires = "; expires="+date.toGMTString();
	} else {
	  expires = "";
	}
	document.cookie = name+"="+value+expires+"; path=/; domain=."+document.domain.replace("www.", "");
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0) === ' ') {
		  c = c.substring(1, c.length);
		}
		if (c.indexOf(nameEQ) === 0) {
		  return c.substring(nameEQ.length, c.length);
		}
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name, "", -1);
}

function verifySiteSeal() {
  var bgHeight = "433";
  var bgWidth = "592";
  var url = "https://seal.godaddy.com:443/verifySeal?sealID=WFJ0kYBejcvrqUOBLCZ6wE56rAymms7C9ehk2bIxUnh8vPhPHudtdkEG2";
  window.open(url,'SealVerfication','location=yes,status=yes,resizable=yes,scrollbars=no,width=' + bgWidth + ',height=' + bgHeight);
}

function popupWindowClips(url) {
  window.open(url,'popupWindow','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes,copyhistory=no,width=700,height=560,screenX=700,screenY=560,top=700,left=560');
}

function popupWindow(url) {
  window.open(url,'popupWindow','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes,copyhistory=no,width=100,height=100,screenX=150,screenY=150,top=150,left=150');
}

function popupWindowBig(url,hei,wid) {
  window.open(url,'popupWindowBig','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no,width='+wid+',height='+hei+',screenX=150,screenY=150,top=150,left=150');
}

function popupDialogUrl(url, w, h, title, modal) {
  if (typeof(title) == 'undefined') { title = ''; }
  if (typeof(modal) == 'undefined') { modal = true; }
  $('<div></div>').appendTo('body').load(url, function(response, status, xhr) {
    var el = this;
    if (status != "error" && response !== '') {
      $(el).dialog({
				modal: modal,
        height: h,
        width: w,
        title: title,
        draggable: true,
        resizable: true,
        close: function() { $(document).unbind('click.popupDialogUrl'); }
      });

      $('.ui-widget-overlay').unbind('click.popupDialogUrl').bind('click.popupDialogUrl', function(e) {
        if (e.button > 0) { return true; }
        $(el).dialog('close');
      });

    } else {
      var post_data = {
        action: 'triggerError',
        errorText: 'Tried to load remote domain URL using $.load. URL: '+url+'. Page: '+window.location.href+'.'
      };
      $.ajax({data:post_data,url:'catalog_ajax.php',type:'POST',dataType:'json',success:function(json){
        popupDialogUrl('need_help.html',800,500);
      }});
    }
  });
}

function navigateToSection(hash_id) {
  window.location.hash = hash_id;
}

function is_valid_email(email) {
	//return (/^[a-zA-Z0-9!#$%&'*+\/=?\^_`{|}~\-]+(?:\.[a-zA-Z0-9!#$%&'*+\/=?\^_`{|}~\-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-]*[a-zA-Z0-9])?/).test(email);
	return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(email);
}

/* ' This is here to fix syntax coloring in jEdit. */

jQuery(document).ready(function() {
  MegaMenu.init();

  $(".thumbnail, a[rel='thumbnail']").livequery(function() { $(this).thumbnailViewer(); });

  $(".moduleRow")
    .live('mouseenter', function() { $(this).addClass("moduleRowOver"); })
    .live('mouseleave', function() { $(this).removeClass("moduleRowOver"); });

  if ($("#headerCartNotification").size() == 1) {
    var buttons = {};
    if ($("#headerCartNotification").attr("cart_page") == "false") { buttons['View Your Cart'] = function() { document.location = '/catalog/shopping_cart.php'; }; }
		if ($("#headerCartNotification").attr("cart_empty") == "false") { buttons['Checkout Now'] = function() { document.location = $("#headerCartNotification").attr("cos_link"); }; }//'/catalog/checkout_shipping.php'; }; }
    buttons['Continue Shopping'] = function() { $(this).dialog('close'); };

    $("#headerCartNotification").dialog({
      disabled: false,
      autoOpen: true,
      buttons: buttons,
      closeOnEscape: true,
      closeText: 'close',
      dialogClass: '',
      draggable: false,
      height: 300,
      //maxHeight: 400,
      maxWidth: 400,
      minHeight: 200,
      minWidth: 400,
      modal: true,
      position: 'center',
      resizable: false,
      stack: true,
      title: $("#headerCartNotification").attr("title"),
      width: 400,
      zIndex: 1000
    });

    $("#headerCartNotification")
      .siblings(".ui-dialog-buttonpane").attr("align", "center")
      .find(".ui-dialog-buttonset").css({ 'float': 'none', 'text-align': 'center' })
      .find("button").attr("class", "coolButton").css({ "margin-left": "10px", "width": "110px" });

    $("div.ui-widget-overlay").unbind("click.headerCartNotification").bind("click.headerCartNotification", function() {
      $("div.ui-widget-overlay").unbind("click.headerCartNotification");
      $("#headerCartNotification").dialog('close');
    });
  }

});


