$(document).ready(function(){
  $('div.navmenugroup').mouseover(function(){
    $(this).next('div.subnavmenu').slideToggle();
  });
  $('div.subnavmenu').bind('mouseleave', function(){
    $(this).slideUp()
  });
});


/* Copyright (c) 2007 Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Version: 1.0.2
 * Requires jQuery 1.1.3+
 * Docs: http://docs.jquery.com/Plugins/livequery
 */
(function($){$.extend($.fn,{livequery:function(type,fn,fn2){var self=this,q;if($.isFunction(type))fn2=fn,fn=type,type=undefined;$.each($.livequery.queries,function(i,query){if(self.selector==query.selector&&self.context==query.context&&type==query.type&&(!fn||fn.$lqguid==query.fn.$lqguid)&&(!fn2||fn2.$lqguid==query.fn2.$lqguid))return(q=query)&&false;});q=q||new $.livequery(this.selector,this.context,type,fn,fn2);q.stopped=false;$.livequery.run(q.id);return this;},expire:function(type,fn,fn2){var self=this;if($.isFunction(type))fn2=fn,fn=type,type=undefined;$.each($.livequery.queries,function(i,query){if(self.selector==query.selector&&self.context==query.context&&(!type||type==query.type)&&(!fn||fn.$lqguid==query.fn.$lqguid)&&(!fn2||fn2.$lqguid==query.fn2.$lqguid)&&!this.stopped)$.livequery.stop(query.id);});return this;}});$.livequery=function(selector,context,type,fn,fn2){this.selector=selector;this.context=context||document;this.type=type;this.fn=fn;this.fn2=fn2;this.elements=[];this.stopped=false;this.id=$.livequery.queries.push(this)-1;fn.$lqguid=fn.$lqguid||$.livequery.guid++;if(fn2)fn2.$lqguid=fn2.$lqguid||$.livequery.guid++;return this;};$.livequery.prototype={stop:function(){var query=this;if(this.type)this.elements.unbind(this.type,this.fn);else if(this.fn2)this.elements.each(function(i,el){query.fn2.apply(el);});this.elements=[];this.stopped=true;},run:function(){if(this.stopped)return;var query=this;var oEls=this.elements,els=$(this.selector,this.context),nEls=els.not(oEls);this.elements=els;if(this.type){nEls.bind(this.type,this.fn);if(oEls.length>0)$.each(oEls,function(i,el){if($.inArray(el,els)<0)$.event.remove(el,query.type,query.fn);});}else{nEls.each(function(){query.fn.apply(this);});if(this.fn2&&oEls.length>0)$.each(oEls,function(i,el){if($.inArray(el,els)<0)query.fn2.apply(el);});}}};$.extend($.livequery,{guid:0,queries:[],queue:[],running:false,timeout:null,checkQueue:function(){if($.livequery.running&&$.livequery.queue.length){var length=$.livequery.queue.length;while(length--)$.livequery.queries[$.livequery.queue.shift()].run();}},pause:function(){$.livequery.running=false;},play:function(){$.livequery.running=true;$.livequery.run();},registerPlugin:function(){$.each(arguments,function(i,n){if(!$.fn[n])return;var old=$.fn[n];$.fn[n]=function(){var r=old.apply(this,arguments);$.livequery.run();return r;}});},run:function(id){if(id!=undefined){if($.inArray(id,$.livequery.queue)<0)$.livequery.queue.push(id);}else
$.each($.livequery.queries,function(id){if($.inArray(id,$.livequery.queue)<0)$.livequery.queue.push(id);});if($.livequery.timeout)clearTimeout($.livequery.timeout);$.livequery.timeout=setTimeout($.livequery.checkQueue,20);},stop:function(id){if(id!=undefined)$.livequery.queries[id].stop();else
$.each($.livequery.queries,function(id){$.livequery.queries[id].stop();});}});$.livequery.registerPlugin('append','prepend','after','before','wrap','attr','removeAttr','addClass','removeClass','toggleClass','empty','remove');$(function(){$.livequery.play();});var init=$.prototype.init;$.prototype.init=function(a,c){var r=init.apply(this,arguments);if(a&&a.selector)r.context=a.context,r.selector=a.selector;if(typeof a=='string')r.context=c||document,r.selector=a;return r;};$.prototype.init.prototype=$.prototype;})(jQuery);

/*
 * jqModal - Minimalist Modaling with jQuery
 *
 * Copyright (c) 2007 Brice Burgess <bhb@iceburg.net>, http://www.iceburg.net
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * 
 * $Version: 2007.08.17 +r11
 * 
 */
(function($) {
$.fn.jqm=function(o){
var _o = {
zIndex: 3000,
overlay: 50,
overlayClass: 'jqmOverlay',
closeClass: 'jqmClose',
trigger: '.jqModal',
ajax: false,
target: false,
modal: false,
toTop: false,
onShow: false,
onHide: false,
onLoad: false
};
return this.each(function(){if(this._jqm)return; s++; this._jqm=s;
H[s]={c:$.extend(_o, o),a:false,w:$(this).addClass('jqmID'+s),s:s};
if(_o.trigger)$(this).jqmAddTrigger(_o.trigger);
});};

$.fn.jqmAddClose=function(e){hs(this,e,'jqmHide'); return this;};
$.fn.jqmAddTrigger=function(e){hs(this,e,'jqmShow'); return this;};
$.fn.jqmShow=function(t){return this.each(function(){if(!H[this._jqm].a)$.jqm.open(this._jqm,t)});};
$.fn.jqmHide=function(t){return this.each(function(){if(H[this._jqm].a)$.jqm.close(this._jqm,t)});};

$.jqm = {
hash:{},
open:function(s,t){var h=H[s],c=h.c,cc='.'+c.closeClass,z=(/^\d+$/.test(h.w.css('z-index')))?h.w.css('z-index'):c.zIndex,o=$('<div></div>').css({height:'100%',width:'100%',position:'fixed',left:0,top:0,'z-index':z-1,opacity:c.overlay/100});h.t=t;h.a=true;h.w.css('z-index',z);
 if(c.modal) {if(!A[0])F('bind');A.push(s);o.css('cursor','wait');}
 else if(c.overlay > 0)h.w.jqmAddClose(o);
 else o=false;

 h.o=(o)?o.addClass(c.overlayClass).prependTo('body'):false;
 if(ie6){$('html,body').css({height:'100%',width:'100%'});if(o){o=o.css({position:'absolute'})[0];for(var y in {Top:1,Left:1})o.style.setExpression(y.toLowerCase(),"(_=(document.documentElement.scroll"+y+" || document.body.scroll"+y+"))+'px'");}}

 if(c.ajax) {var r=c.target||h.w,u=c.ajax,r=(typeof r == 'string')?$(r,h.w):$(r),u=(u.substr(0,1) == '@')?$(t).attr(u.substring(1)):u;
  r.load(u,function(){if(c.onLoad)c.onLoad.call(this,h);if(cc)h.w.jqmAddClose($(cc,h.w));e(h);});}
 else if(cc)h.w.jqmAddClose($(cc,h.w));

 if(c.toTop&&h.o)h.w.before('<span id="jqmP'+h.w[0]._jqm+'"></span>').insertAfter(h.o);	
 (c.onShow)?c.onShow(h):h.w.show();e(h);return false;
},
close:function(s){var h=H[s];h.a=false;
 if(A[0]){A.pop();if(!A[0])F('unbind');}
 if(h.c.toTop&&h.o)$('#jqmP'+h.w[0]._jqm).after(h.w).remove();
 if(h.c.onHide)h.c.onHide(h);else{h.w.hide();if(h.o)h.o.remove();} return false;
}};
var s=0,H=$.jqm.hash,A=[],ie6=$.browser.msie&&($.browser.version == "6.0"),
i=$('<iframe src="javascript:false;document.write(\'\');" class="jqm"></iframe>').css({opacity:0}),
e=function(h){if(ie6)if(h.o)h.o.html('<p style="width:100%;height:100%"/>').prepend(i);else if(!$('iframe.jqm',h.w)[0])h.w.prepend(i); f(h);},
f=function(h){try{$(':input:visible',h.w)[0].focus();}catch(e){}},
F=function(t){$()[t]("keypress",m)[t]("keydown",m)[t]("mousedown",m);},
m=function(e){var h=H[A[A.length-1]],r=(!$(e.target).parents('.jqmID'+h.s)[0]);if(r)f(h);return !r;},
hs=function(w,e,y){var s=[];w.each(function(){s.push(this._jqm)});
 $(e).each(function(){if(this[y])$.extend(this[y],s);else{this[y]=s;$(this).click(function(){for(var i in {jqmShow:1,jqmHide:1})for(var s in this[i])if(H[this[i][s]])H[this[i][s]].w[i](this);return false;});}});};
})(jQuery);


(function($){$.fn.fieldValue=function(successful){for(var val=[],i=0,max=this.length;i<max;i++){var el=this[i];var v=$.fieldValue(el,successful);if(v===null||typeof v=='undefined'||(v.constructor==Array&&!v.length))continue;v.constructor==Array?$.merge(val,v):val.push(v);}return val;};$.fieldValue=function(el,successful){var n=el.name,t=el.type,tag=el.tagName.toLowerCase();if(typeof successful=='undefined')successful=true;if(successful&&(!n||el.disabled||t=='reset'||t=='button'||(t=='checkbox'||t=='radio')&&!el.checked||(t=='submit'||t=='image')&&el.form&&el.form.clk!=el||tag=='select'&&el.selectedIndex==-1))return null;if(tag=='select'){var index=el.selectedIndex;if(index<0)return null;var a=[],ops=el.options;var one=(t=='select-one');var max=(one?index+1:ops.length);for(var i=(one?index:0);i<max;i++){var op=ops[i];if(op.selected){var v=$.browser.msie&&!(op.attributes['value'].specified)?op.text:op.value;if(one)return v;a.push(v);}}return a;}return el.value;};})(jQuery);


//model
function do_cart_add(json){
  if (json[0].success) {
    cart_flyout = $("#cart-flyout");
    cart_flyout.html(json[0].html);
    $("#num_cart_items").html(json[0].num_items);
    
    options = 
    {
      overlay: 1,
      onShow: function(hash) { 
        cart_flyout.slideDown("fast");
      },
      onHide: function(hash) { 
        hash.w.fadeOut('500',function(){ 
          hash.o.remove(); 
        });
      }
    };
    cart_flyout.jqm(options).jqmShow();
    if (json[0].newitem_html) {
      $("#cartmain").append(json[0].newitem_html);
    } else {
      do_cart_save(json);
    }
    
    
  } else {
    alert('Error adding item to the cart');
  }
}


//checkout/model
function cart_freight(){
  var zip = $("#zip").val();
  var url = 'cart-process.php?action=freight&zip=' + zip;
  $('#freight_cost').html('Loading <img src="/js/grey-loading.gif"/>');
  $.getJSON(url, {}, function(json){
    refresh_cart(json[0]);
    
  });
  /*
this.blur();return false;
*/
}


//checkout/model
function check_quantity(quantity, quantityunit, lowqty){
  quantity = parseInt(quantity);
  quantityunit = parseInt(quantityunit);
  lowqty = parseInt(lowqty);
  var error = '';
  if (quantity % quantityunit != 0) {
    error += "The quantity must be a multiple of " + quantityunit + ".\n";
  }
  if (quantity < lowqty) {
    var itemtext = (lowqty > 1) ? ' units' : ' unit';
    error += "There is a minimum order of " + lowqty + " " + itemtext + ".\n";
  }
  return error;
}

//checkout/model
function check_swatches(swatches){
  var error = '';
  var allselected = 1;
  swatches.each(function(i){
    if (this.value == '') {
      $(this).css("border", "2px dotted red");
      allselected = 0;
    } else {
      $(this).css("border", "0px");
    }
  });
  
  if (!allselected) {
    error += "Please select all swatches.\n";
  }
  return error;
}

//checkout/model
function check_swatch(swatch){
  var valid = true;
  if (this.value == '') {
    $(this).css("border", "2px dotted red");
    valid = false;
  } else {
    $(this).css("border", "0px");
  }
  return valid;
}

// general function for adding and edit/saving items
//checkout /model
function save_cart_item(form_ref){
  if ( form_ref.indexOf('model_')>-1) {
    var local_form = $("#" + form_ref);
    var target = $("input[name='target']", local_form).val();
    var action = 'add';
  } else {
    var cart_item_id = form_ref;
    var local_form = $('#cart_item_' + cart_item_id);
    var action = 'save';
  }
  var model_no = $("input[name='model_no']", local_form).val();
  var target   = $("input[name='target']", local_form).val();
  var quantity = $("input[name='quantity']", local_form).val();
  var swatches = $("select[name^='swid']", local_form); // array
  var quantityunit = $("input[name='quantityunit']", local_form).val();
  var lowqty = $("input[name='lowqty']", local_form).val();
  var stid = $("input[@name='stid']", local_form).fieldValue();
  
  var error = check_quantity(quantity, quantityunit, lowqty);
  error += check_swatches(swatches);
  
  if (error != '') {
    alert(error);
  } else {
    swatch_str = '';
    swatches.each(function(){
      swatch_str += this.name + "=" + this.value + "&";
    });
    
    var url = "/cart-process.php?action=" + action;
    url += (action == 'save') ? "&cart_item_id=" + cart_item_id : "&model_no=" + model_no;
    url += "&" + swatch_str + "quantity=" + quantity + "&stid=" + stid;
    url += (target=='cart_page')?'&target=cart_page' : '';
    
    $.getJSON(url, {}, function(json){
      if (action == 'save') {
        do_cart_save(json);
      } else {
        do_cart_add(json);
      }
    });
  }
}
// - until here - general page - after here checkout
// checkout
function do_cart_save(json){
  if (json[0].success) {
    // if the cart_item was changed to match a different cart item
    if (json[0].duplicate > 0) {
      $("#cartitem_" + json[0].cart_item_id).fadeOut();
      load_cart_item(json[0].duplicate, 1);
      refresh_cart(json[0]);
    } else {
      $("#cartitem_" + json[0].cart_item_id).replaceWith(json[0].html);
      refresh_cart(json[0]);
    }
    $("#num_cart_items").html(json[0].num_items);
  } else {
    alert('Error saving item in cart.');
  }
}


//only checkout
function reset_cart_item(cart_item_id){
  load_cart_item(cart_item_id, 1);
}

// checkout
function load_cart_item(cart_item_id, reset){
  var edit = (reset == 1) ? '&edit=0' : '';
  var cart_item = $("#cartitem_" + cart_item_id);
  
  var url = '/cart-process.php?action=load&cart_item_id=' + cart_item_id + edit;
  
  $.getJSON(url, {}, function(json){
    if (json[0].success) {
      cart_item.replaceWith(json[0].html);
    } else {
      success = false;
      alert('Error loading item.');
    }
  });
}

function confirm_delete(cart_item_id, delete_item_text) 
{
  
  $("#delete_item_text").html(delete_item_text)
  $('#do_remove_cart_item').unbind('click').click(function(){
    delete_from_cart(cart_item_id);
    $('#deleteprompt').jqmHide();
    return false;
    });
    
    
  $('#deleteprompt').jqm().jqmShow();
    
    
  
}

//checkout
function delete_from_cart(cart_item_id){
  var cart_item = $("#cartitem_" + cart_item_id);
  var url = '/cart-process.php?action=delete&cart_item_id=' + cart_item_id;
  $.getJSON(url, {}, function(json){
    if (json[0].success) {
      cart_item.css(
      {
        border: "1px solid red",
        background: "#FBE6F2"
      }).fadeOut(1000);
      refresh_cart(json[0]);
    } else {
      success = false;
      alert('Error deleting item from cart.');
    }
  });
}

//checkout
function refresh_cart(json){
  if (json.subtotal_text) {
    $("#sub_total").html(json.subtotal_text);
  }
  
  if (json.freight_text) {
    $("#calculatefreight").html(json.freight_text);
  } 
  $("#googlecart").load("/gcart.php");
}

$(document).ready(function(){
	$("h3.accessory_expand").livequery('click',function(){
    if ($(this).hasClass('activeaccessory')) {
      $(this).removeClass('activeaccessory').text('Click here to show accessories for this product').next(".cartitemaccessories").slideUp();
    } else {
      $(this).addClass('activeaccessory').text('Click here to hide accessories for this product').next(".cartitemaccessories").slideToggle();
    }
  });
  $(".accessoryaddtocart").livequery('click',function(){
    save_cart_item($(this).parents('form').attr('id'));
  });
});


// JavaScript Document// JavaScript Document//Chrome Drop Down Menu- Author: Dynamic Drive (http://www.dynamicdrive.com)
//Last updated: June 14th, 06'

var cssdropdown={
disappeardelay: 600, //set delay in miliseconds before menu disappears onmouseout
disablemenuclick: true, //when user clicks on a menu item with a drop down menu, disable menu item's link?
enableswipe: 1, //enable swipe effect? 1 for yes, 0 for no

//No need to edit beyond here////////////////////////
dropmenuobj: null, ie: document.all, firefox: document.getElementById&&!document.all, swipetimer: undefined, bottomclip:0,

getposOffset:function(what, offsettype){
var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
var parentEl=what.offsetParent;
while (parentEl!=null){
totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
parentEl=parentEl.offsetParent;
}
return totaloffset;
},

swipeeffect:function(){
if (this.bottomclip<parseInt(this.dropmenuobj.offsetHeight)){
this.bottomclip+=10+(this.bottomclip/10) //unclip drop down menu visibility gradually
this.dropmenuobj.style.clip="rect(0 auto "+this.bottomclip+"px 0)"
}
else
return
this.swipetimer=setTimeout("cssdropdown.swipeeffect()", 10)
},

showhide:function(obj, e){
if (this.ie || this.firefox)
this.dropmenuobj.style.left=this.dropmenuobj.style.top="-500px"
if (e.type=="click" && obj.visibility==hidden || e.type=="mouseover"){
if (this.enableswipe==1){
if (typeof this.swipetimer!="undefined")
clearTimeout(this.swipetimer)
obj.clip="rect(0 auto 0 0)" //hide menu via clipping
this.bottomclip=0
this.swipeeffect()
}
obj.visibility="visible"
}
else if (e.type=="click")
obj.visibility="hidden"
},

iecompattest:function(){
return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
},

clearbrowseredge:function(obj, whichedge){
var edgeoffset=0
if (whichedge=="rightedge"){
var windowedge=this.ie && !window.opera? this.iecompattest().scrollLeft+this.iecompattest().clientWidth-15 : window.pageXOffset+window.innerWidth-15
this.dropmenuobj.contentmeasure=this.dropmenuobj.offsetWidth
if (windowedge-this.dropmenuobj.x < this.dropmenuobj.contentmeasure)  //move menu to the left?
edgeoffset=this.dropmenuobj.contentmeasure-obj.offsetWidth
}
else{
var topedge=this.ie && !window.opera? this.iecompattest().scrollTop : window.pageYOffset
var windowedge=this.ie && !window.opera? this.iecompattest().scrollTop+this.iecompattest().clientHeight-15 : window.pageYOffset+window.innerHeight-18
this.dropmenuobj.contentmeasure=this.dropmenuobj.offsetHeight
if (windowedge-this.dropmenuobj.y < this.dropmenuobj.contentmeasure){ //move up?
edgeoffset=this.dropmenuobj.contentmeasure+obj.offsetHeight
if ((this.dropmenuobj.y-topedge)<this.dropmenuobj.contentmeasure) //up no good either?
edgeoffset=this.dropmenuobj.y+obj.offsetHeight-topedge
}
}
return edgeoffset
},

dropit:function(obj, e, dropmenuID){
if (this.dropmenuobj!=null) //hide previous menu
this.dropmenuobj.style.visibility="hidden" //hide menu
this.clearhidemenu()
if (this.ie||this.firefox){
obj.onmouseout=function(){cssdropdown.delayhidemenu()}
obj.onclick=function(){return !cssdropdown.disablemenuclick} //disable main menu item link onclick?
this.dropmenuobj=document.getElementById(dropmenuID)
this.dropmenuobj.onmouseover=function(){cssdropdown.clearhidemenu()}
this.dropmenuobj.onmouseout=function(){cssdropdown.dynamichide(e)}
this.dropmenuobj.onclick=function(){cssdropdown.delayhidemenu()}
this.showhide(this.dropmenuobj.style, e)
this.dropmenuobj.x=this.getposOffset(obj, "left")
this.dropmenuobj.y=this.getposOffset(obj, "top")
this.dropmenuobj.style.left=this.dropmenuobj.x-this.clearbrowseredge(obj, "rightedge")+"px"
this.dropmenuobj.style.top=this.dropmenuobj.y-this.clearbrowseredge(obj, "bottomedge")+obj.offsetHeight+1+"px"
}
},

contains_firefox:function(a, b) {
while (b.parentNode)
if ((b = b.parentNode) == a)
return true;
return false;
},

dynamichide:function(e){
var evtobj=window.event? window.event : e
if (this.ie&&!this.dropmenuobj.contains(evtobj.toElement))
this.delayhidemenu()
else if (this.firefox&&e.currentTarget!= evtobj.relatedTarget&& !this.contains_firefox(evtobj.currentTarget, evtobj.relatedTarget))
this.delayhidemenu()
},

delayhidemenu:function(){
this.delayhide=setTimeout("cssdropdown.dropmenuobj.style.visibility='hidden'",this.disappeardelay) //hide menu
},

clearhidemenu:function(){
if (this.delayhide!="undefined")
clearTimeout(this.delayhide)
},

startchrome:function(){
for (var ids=0; ids<arguments.length; ids++){
var menuitems=document.getElementById(arguments[ids]).getElementsByTagName("a")
for (var i=0; i<menuitems.length; i++){
if (menuitems[i].getAttribute("rel")){
var relvalue=menuitems[i].getAttribute("rel")
menuitems[i].onmouseover=function(e){
var event=typeof e!="undefined"? e : window.event
cssdropdown.dropit(this,event,this.getAttribute("rel"))
}
}
}
}
}

}


function loadFreight() {
  $('#freightcost').html('Loading <img src="/js/loading.gif"/>');
  zip 	   	 = $('#zip').val();
  model_no   = $("#model_no").val();
  unit_price = $("span.main_price").text().split('$')[1];
  quantity   = $('#quantity').val()
		    
  var freight_url;
  freight_url = '/includes/presentation/popup_freight.php'
  + '?zip='		 + zip 
	+ '&model_no='   + model_no
	+ '&unit_price=' + unit_price
	+ '&quantity='   + quantity;
  $('#freightcost').load(freight_url);
  this.blur();
  return false;
} 

$(document).ready(function() {
	$('#freightCheck').click(loadFreight);
});

