/// <reference path="jquery.vsdoc.js" />

/// Product Detail Functions ///

// Ajax call to add item to cart 
function AddToCart() {
    // Grab vars from hidden fields
    var size = $("input[name = 'szID']:checked").val();
    var colour = $("input[name = 'clID']").val();
    var prod = $("input[name = 'pdID']").val();
    var cat = $("input[name = 'catID']").val();
    var quantity  = $("input[name = 'szID']:checked").parent().nextAll("td.quantity").children("input").val();

    if (quantity > 0 && size >= 0) {
        $.ajax({
            type: "GET",
            url: "/default.aspx",
            cache: false,
            data: { z: "c", action: "additem", pdID: prod, catID: cat, szID: size, clID: colour, qty: quantity, addpopup: "1" },
            success: ShowAddToCartPopup
        });
    } else {
        alert("Please select your preference and quantity you require before adding this item to your cart.");
    }

    return false; // Prevent form submit
}

function GetCartPopup() {
    data = {
        "z": "c",
        "action" : "cart",
        "cartpopup": "1"
    }
    $.post("/", data, ShowCartPopup);
    return false; // Prevent form submit
}

// Show cart popup with given html data
var cartTimeout

function ShowAddToCartPopup(data) {
    var cartPopup = $("#cart_summary_holder");
    // Stop any animations running and timeouts
    cartPopup.stop();
    window.clearTimeout(cartTimeout);
    
    // Set and show data, setup scrolling and fade out 
    cartPopup.html(data);
    ScrollCartPopup();
    cartPopup.show();
    $(window).scroll(ScrollCartPopup);
    
    cartTimeout = window.setTimeout(function() { cartPopup.fadeOut(); $(window).unbind("scroll", ScrollCartPopup); }, 5000);
}

function ScrollCartPopup() {
    ScrollPopup("#cart_summary_holder > div");
}

// Get popup in view
function ScrollPopup(selector) {
    var y;
    if (self.pageYOffset) {
        y = self.pageYOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {
        y = document.documentElement.scrollTop;
    } else if (document.body) {
        y = document.body.scrollTop;
    }

    $(selector).css("top", y + "px");
}

// Called when a product item is selected
function ItemSelected() {
    var qty = $("input[name = 'szID']:checked").parent().nextAll("td.quantity").children("input");
    $("td.quantity").children("input").css("visibility", "hidden"); // Hide all and ..
    qty.css("visibility", "visible");                               // Show current
    
    // Set display qty field to 1 if it's blank
    if (qty.val() == "") {
        qty.val("1");
    }
}

// Cart Popup Summary, similar to add to cart except no auto fadeout
function ShowCartPopup(data) {
    var cartPopup = $("#cart_summary_holder");
    // Stop any animations running and timeouts
    cartPopup.stop();
    window.clearTimeout(cartTimeout);
    
    // Set and show data, setup scrolling and fade out 
    cartPopup.html(data);
    ScrollCartPopup();
    cartPopup.show();
    $(window).scroll(ScrollCartPopup);
//    cartTimeout = window.setTimeout(function() { cartPopup.fadeOut(); $(window).unbind("scroll", ScrollCartPopup); }, 5000);
}

$(function() {
    $("#login-button").keypress(function(e) {
        if (e.which == 13) $("#login-form").submit();
    });
    ItemSelected(); // Called once here for when there is a prechecked item
    $("input[name = 'szID']").click(ItemSelected);
    $("input.AddToCartButton").click(AddToCart);
    $("#show-write-a-review").click(ShowProductReviewForm);
    $("#add-to-favourites").click(AddToList);
    $("#add-to-favourites-login").click(function() {
        ShowLoginBox("Please login first before adding to your favourites");
        $("#login-box-productcode").val(escape(window.location.pathname));
        return false;
    });

    $("#show-email-a-friend").click(ShowEmailAFriendForm);

    // Header show popup events
    $("#CartSummary_items").click(function() { GetCartPopup(); ScrollCartPopup(); return false; });
    $("#show-login-box").click(function() { ShowLoginBox(); return false; });
});


// Show the login box, optionally changing the default message displayed
function ShowLoginBox(message) {
    if (message != undefined && message.length > 0) {
        $("#login-box-message").text(message);
    }

    ScrollPopup("#login_form_holder > div");
    $(window).scroll(function() { ScrollPopup("#login_form_holder > div"); });
    $("#login_form_holder").show();
}

// ## Email a friend ##

function ShowEmailAFriendForm() {
    var eventObj = this;
    var prod = parseInt($("input[name = 'pdID']").val());
    if (prod > 0) {
        $.get(
            "/",
            { z: "emailafriend", action: "displayform", pdID: prod }, function(data) {
                $("#email-a-friend").html(data);
                popup(2, 'email-a-friend', eventObj);
                InitEmailAFriendForm();
            }
        );
    }
    return false;
}

function InitEmailAFriendForm() {
    $("div.email_a_friend form").submit(function() {
        $("#email-a-friend-progress").css("visibility", "visible");
        $("#email-a-friend-messages").hide();
        $.post(
        "/", $("div.email_a_friend form").serializeArray(), function(data) {
            $("#email-a-friend-progress").css("visibility", "hidden");
            $("#email-a-friend-messages").html(data);
            $("#email-a-friend-messages").slideDown();
        }
        );
        return false;
    });
}

// ## Favourites/Wishlist/Orderlist ##

function AddToList() {
    // Grab vars from hidden fields
    var size = $("input[name = 'szID']:checked").val();
    var colour = $("input[name = 'clID']").val();
    var prod = $("input[name = 'pdID']").val();
    var cat = $("input[name = 'catID']").val();
    var quantity = $("input[name = 'szID']:checked").parent().nextAll("td.quantity").children("input").val();
    var wid = $("input[name = 'wid']").val();


    if (size == undefined || size.length == 0) {
        alert("Please select your preference for which size/flavour of this product you'd like added to your favourites first.")
        return false;
    }
    
    if (quantity == undefined || quantity.length == 0) { quantity = 1; }

    data = {
        "z": "c",
        "action": "orderlist",
        "ol": "additem",
        "pdID": prod,
        "catID": cat,
        "szID": size,
        "clID": colour,
        "qty": quantity,
        "addpopup": "1"
    }

    if (wid != undefined && wid > 0) {
        data["wid"] = wid;
    } else {
        data["new"] = 1;
    }
    
    if (quantity > 0 && size >= 0) {
        $.post("/", data, ShowAddToCartPopup);
    } else {
        alert("Please select your preference and quantity you require before adding this item to your cart.");
    }

    return false; // Prevent form submit
}

// ## Product Review ##

// Attach event handlers
function InitProductReview() {
    $("#ProductReviewForm").submit(function() {
        $("#ProductReviewFormProgress").css("visibility", "visible");
        $("#ReviewFormMessages").hide();
        $.post(
            "/default.aspx", $("#ProductReviewForm").serializeArray(), function(data) {
                $("#ProductReviewFormProgress").css("visibility", "hidden");
                $("#ReviewFormMessages").html(data);
                $("#ReviewFormMessages").slideDown();
            }
        );
        return false;
    });
}

// AJAX call to show product review form
function ShowProductReviewForm() {
    var eventObj = this;
    var prod = parseInt($("input[name = 'pdID']").val());
    if (prod > 0) {
        $.get(
            "/default.aspx",
            { z: "review", pdID: prod }, function(data) {
                $("#write_review").html(data);
                popup(2, 'write_review', eventObj);
                InitProductReview();
            }
        );
    }
    return false;
}

/// Designer Functions ///

function cmxform(){
  // Hide forms
  $( 'form.cmxform' ).hide().end();

  // Processing
  $( 'form.cmxform' ).find( 'li/label' ).not( '.nocmx' ).each( function( i ){
    var labelContent = this.innerHTML;
    var labelWidth = document.defaultView.getComputedStyle( this, '' ).getPropertyValue( 'width' );
    var labelSpan = document.createElement( 'span' );
        labelSpan.style.display = 'block';
        labelSpan.style.width = labelWidth;
        labelSpan.innerHTML = labelContent;
    this.style.display = '-moz-inline-box';
    this.innerHTML = null;
    this.appendChild( labelSpan );
  } ).end();

  // Show forms
  $( 'form.cmxform' ).show().end();
}

(function($) {
jQuery.fn.pngFix = function(settings) {
	// Settings
	settings = jQuery.extend({
		blankgif: '/images/1px.gif'
	}, settings);
	var ie55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1);
	var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);
	if (jQuery.browser.msie && (ie55 || ie6)) {
		//fix images with png-source
		jQuery(this).find("img[src$=.png]").each(function() {
			jQuery(this).attr('width',jQuery(this).width());
			jQuery(this).attr('height',jQuery(this).height());
			var prevStyle = '';
			var strNewHTML = '';
			var imgId = (jQuery(this).attr('id')) ? 'id="' + jQuery(this).attr('id') + '" ' : '';
			var imgClass = (jQuery(this).attr('class')) ? 'class="' + jQuery(this).attr('class') + '" ' : '';
			var imgTitle = (jQuery(this).attr('title')) ? 'title="' + jQuery(this).attr('title') + '" ' : '';
			var imgAlt = (jQuery(this).attr('alt')) ? 'alt="' + jQuery(this).attr('alt') + '" ' : '';
			var imgAlign = (jQuery(this).attr('align')) ? 'float:' + jQuery(this).attr('align') + ';' : '';
			var imgHand = (jQuery(this).parent().attr('href')) ? 'cursor:hand;' : '';
			if (this.style.border) {
				prevStyle += 'border:'+this.style.border+';';
				this.style.border = '';
			}
			if (this.style.padding) {
				prevStyle += 'padding:'+this.style.padding+';';
				this.style.padding = '';
			}
			if (this.style.margin) {
				prevStyle += 'margin:'+this.style.margin+';';
				this.style.margin = '';
			}
			var imgStyle = (this.style.cssText);
			strNewHTML += '<span '+imgId+imgClass+imgTitle+imgAlt;
			strNewHTML += 'style="position:relative;white-space:pre-line;display:inline-block;background:transparent;'+imgAlign+imgHand;
			strNewHTML += 'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;';
			strNewHTML += 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + jQuery(this).attr('src') + '\', sizingMethod=\'scale\');';
			strNewHTML += imgStyle+'"></span>';
			if (prevStyle != ''){
				strNewHTML = '<span style="position:relative;display:inline-block;'+prevStyle+imgHand+'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;'+'">' + strNewHTML + '</span>';
			}

			jQuery(this).hide();
			jQuery(this).after(strNewHTML);

		});
		// fix css background pngs
		//jQuery(this).find("*").each(function(){
			//var bgIMG = jQuery(this).css('background-image');
			//if(bgIMG.indexOf(".png")!=-1){
			//	var iebg = bgIMG.split('url("')[1].split('")')[0];
			//	jQuery(this).css('background-image', 'none');
			//	jQuery(this).get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + iebg + "',sizingMethod='scale')";
			//}
		//});		
		//fix input with png-source
		jQuery(this).find("input[src$=.png]").each(function() {
			var bgIMG = jQuery(this).attr('src');
			jQuery(this).get(0).runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + bgIMG + '\', sizingMethod=\'scale\');';
   		jQuery(this).attr('src', settings.blankgif)
		});	
	}	
	return jQuery;
};
})(jQuery);


;(function(){var $$;$$=jQuery.fn.flash=function(htmlOptions,pluginOptions,replace,update){var block=replace||$$.replace;pluginOptions=$$.copy($$.pluginOptions,pluginOptions);if(!$$.hasFlash(pluginOptions.version)){if(pluginOptions.expressInstall&&$$.hasFlash(6,0,65)){var expressInstallOptions={flashvars:{MMredirectURL:location,MMplayerType:'PlugIn',MMdoctitle:jQuery('title').text()}};}else if(pluginOptions.update){block=update||$$.update;}else{return this;}}htmlOptions=$$.copy($$.htmlOptions,expressInstallOptions,htmlOptions);return this.each(function(){block.call(this,$$.copy(htmlOptions));});};$$.copy=function(){var options={},flashvars={};for(var i=0;i<arguments.length;i++){var arg=arguments[i];if(arg==undefined)continue;jQuery.extend(options,arg);if(arg.flashvars==undefined)continue;jQuery.extend(flashvars,arg.flashvars);}options.flashvars=flashvars;return options;};$$.hasFlash=function(){if(/hasFlash\=true/.test(location))return true;if(/hasFlash\=false/.test(location))return false;var pv=$$.hasFlash.playerVersion().match(/\d+/g);var rv=String([arguments[0],arguments[1],arguments[2]]).match(/\d+/g)||String($$.pluginOptions.version).match(/\d+/g);for(var i=0;i<3;i++){pv[i]=parseInt(pv[i]||0);rv[i]=parseInt(rv[i]||0);if(pv[i]<rv[i])return false;if(pv[i]>rv[i])return true;}return true;};$$.hasFlash.playerVersion=function(){try{try{var axo=new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');try{axo.AllowScriptAccess='always';}catch(e){return'6,0,0';}}catch(e){}return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g,',').match(/^,?(.+),?$/)[1];}catch(e){try{if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){return(navigator.plugins["Shockwave Flash 2.0"]||navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g,",").match(/^,?(.+),?$/)[1];}}catch(e){}}return'0,0,0';};$$.htmlOptions={flashvars:{},pluginspage:'http://www.adobe.com/go/getflashplayer',src:'#',type:'application/x-shockwave-flash'};$$.pluginOptions={expressInstall:false,update:true,version:'6.0.65'};$$.replace=function(htmlOptions){this.innerHTML='<div class="alt">'+this.innerHTML+'</div>';jQuery(this).addClass('flash-replaced').prepend($$.transform(htmlOptions));};$$.update=function(htmlOptions){var url=String(location).split('?');url.splice(1,0,'?hasFlash=true&');url=url.join('');var msg='<p>This content requires the Flash Player. <a href="http://www.adobe.com/go/getflashplayer">Download Flash Player</a>. Already have Flash Player? <a href="'+url+'">Click here.</a></p>';this.innerHTML='<span class="alt">'+this.innerHTML+'</span>';jQuery(this).addClass('flash-update').prepend(msg);};function toAttributeString(){var s='';for(var key in this)if(typeof this[key]!='function')s+=key+'="'+this[key]+'" ';return s;};function toFlashvarsString(){var s='';for(var key in this)if(typeof this[key]!='function')s+=key+'='+encodeURIComponent(this[key])+'&';return s.replace(/&$/,'');};$$.transform=function(htmlOptions){htmlOptions.toString=toAttributeString;if(htmlOptions.flashvars)htmlOptions.flashvars.toString=toFlashvarsString;return'<embed '+String(htmlOptions)+'/>';};if(window.attachEvent){window.attachEvent("onbeforeunload",function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};});}})();

/** jquery sifr embedding **/
jQuery.fn.sifr=function(prefs){var p=jQuery.extend((prefs===false)?{unsifr:true}:{},arguments.callee.prefs,prefs);if(p.save){arguments.callee.prefs=jQuery.extend(p,{save:false});}if(this[0]===document){return;}if(!p.unsifr&&typeof p.before==='function'){p.before.apply(this,[p]);}this.each(function(){var t=jQuery(this);var a=t.children('.sIFR-alternate');if(a.html()){t.html(a.html());if(p.unsifr){return;}}if(typeof p.beforeEach==='function'){p.beforeEach.apply(this,[t,p]);}var s=t.html('<span class="flash-replaced sIFR-replaced">'+(p.content||t.html()).replace(/^\s+|\s+$/g,'')+'</span>').children();a=t.append('<span class="alt sIFR-alternate">'+s.html()+'</span>').children('.sIFR-alternate');if(a.css('display')!=='none'){a.css('display','none');}var toHex=function(c){var h=function(n){if(n===0||isNaN(n)){return'00';}n=Math.round(Math.min(Math.max(0,n),255));return'0123456789ABCDEF'.charAt((n-n%16)/16)+'0123456789ABCDEF'.charAt(n%16);};c=(c)?c.replace(/rgb|\(|\)|#$/g,''):false;if(!c){return false;}if(c.indexOf(',')>-1){c=c.split(', ');return'#'+h(c[0])+h(c[1])+h(c[2]);}if(c.search('#')>-1&&c.length<=4){c=c.split('');return'#'+c[1]+c[1]+c[2]+c[2]+c[3]+c[3];}return c;};if(p.textTransform){if(p.textTransform.toLowerCase()==='uppercase'){s.html(s.html().toUpperCase());}if(p.textTransform.toLowerCase()==='lowercase'){s.html(s.html().toLowerCase());}if(p.textTransform.toLowerCase()==='capitalize'){var c=s.html().replace(/\>/g,'> ').split(' ');for(var i=0;i<c.length;i=i+1){c[i]=c[i].charAt(0).toUpperCase()+c[i].substring(1);}s.html(c.join(' ').replace(/\> /g,'>'));}}var f={flashvars:jQuery.extend({h:s.height()*(p.zoom||1),offsetLeft:p.offsetLeft||undefined,offsetTop:p.offsetTop||undefined,textAlign:p.textAlign||(/(left|center|right)/.exec(t.css('textAlign'))||['center'])[0],textColor:toHex(p.color||t.css('color'))||undefined,txt:p.content||s.html(),underline:(p.underline||(p.underline!==false&&t.css('textDecoration')==='underline'))?true:undefined,w:(p.width||s.width())*(p.zoom||1)},p.flashvars),height:p.height||s.height(),src:(p.path||'')+((p.path&&p.path.substr(p.path.length-1)!=='/')?'/':'')+(p.font||'')+((p.font&&p.font.indexOf('.swf')===-1)?'.swf':''),width:p.width||s.width(),wmode:'transparent'};f.flashvars.linkColor=toHex(p.link||t.find('a').css('color'))||f.flashvars.textColor;f.flashvars.hoverColor=toHex(p.hover)||f.flashvars.linkColor;if(p.zoom){f.flashvars.offsetTop=((p.offsetTop||0)+((s.height()-(s.height()*p.zoom))/2))*(p.zoomTop||1);f.flashvars.offsetLeft=((p.offsetLeft||0)+((s.width()-(s.width()*p.zoom))/2))*(p.zoomLeft||1);}t.flash(jQuery.extend(f,p.embedOptions),jQuery.extend({expressInstall:p.expressInstall||false,version:p.version||7,update:p.update||false},p.pluginOptions),function(f){var preHeight=t.height();var preWidth=t.width();s.html(jQuery.fn.flash.transform(f));var e=s.find(':first');e.css({verticalAlign:'text-bottom',display:'inline',width:p.width,height:p.height});var marginBottom=preHeight-t.height();var width=parseInt(e.css('width'),10)+parseInt(preWidth-t.width(),10);if(!p.height){e.css({marginBottom:marginBottom});}if(!p.width){e.css({width:width});}if(p.height&&p.verticalAlign==='middle'){e.css({marginTop:Math.floor((p.height-s.height())/2),marginBottom:Math.round((p.height-s.height())/2),height:s.height()});e.attr('height',s.height());}if(p.height&&p.verticalAlign==='bottom'){var a=t.find('.sIFR-alternate');e.css({marginTop:(p.height-s.height()),height:s.height()});e.attr('height',s.height());}if(p.css){e.css(p.css);}});if(typeof p.afterEach==='function'){p.afterEach.apply(this,[t,p]);}});if(!p.unsifr&&typeof p.after==='function'){p.after.apply(this,[p]);}};jQuery.sifr=function(prefs){jQuery().sifr(jQuery.extend({save:true},prefs));};jQuery.fn.unsifr=function(){return this.each(function(){jQuery(this).sifr(false);});};


/* tabulate */
(function($){   
 $.fn.tabulate = function(opts) {  
    var defaults = {  
		cell_selector:'.Item',
		table_width:0,
		cell_width:0
    };   
    var o = $.extend(defaults, opts);  
    return this.each(function() { 
		var selfref=$(this);		
        var cells = $(o.cell_selector,selfref).css({'float':'left','display':'block'});
		var availableW;
		if(o.table_width > 0){availableW = o.table_width;}else{availableW = selfref.innerWidth()}
		var cellW;
		if(o.cell_width > 0){cellW = o.cell_width;}else{cellW = cells.outerWidth();}	
		var cols = Math.floor(availableW/cellW);
		
		if(cols < 1){cols=1;}
		if(cells.length > 0){
			cells.each(function(i){
				if(i%cols == cols-1 || i == cells.length-1){
					$(this).after($('<div class="divider" style="clear:left"></div>'));
				}
			});				
			var heights=[];
			function setHeights(e){				
				cells.each(function(i){
					var myRow=Math.floor(i/cols);
					$(this).css("height","auto");
					var myH = $(this).height();
					if(heights[myRow]==undefined || heights[myRow]==null || heights[myRow] < myH){
						heights[myRow]=myH;
					}
				});	
				cells.each(function(i){
					var myRow=Math.floor(i/cols);
					 $(this).css("min-height",heights[myRow]+"px");				
				});				
			}
			$('img',cells).bind('load',function(e){setHeights(e);});
			setHeights();			
		}
    });   
 };   
})(jQuery);

(function($){   
 $.fn.make_tabs = function(opts) {  
    var defaults = {  
		item_selector:'.info_item',
		link_selector:'.info_heading',
		content_selector:'.info_content'
    };   
    var o = $.extend(defaults, opts); 
	
    return this.each(function() { 
		var selfref=$(this);
		var tabend=$('<span class="tab_end"><img alt="" src="/images/spacer.gif"/></span>')
		var links=	$(o.link_selector +' h3',selfref).each(function(){
			var t=$(this);
			if(!(t.children('span:last-child').hasClass('tab_end'))){
				t.append(tabend);
			}
		});
		if(links.length>1){
			links.css('cursor','pointer');
		}
		selfref.displayHolder = $('<div class="tab_display"></div>')
		$(o.item_selector+':last',selfref).addClass("last").after(selfref.displayHolder);
		selfref.showItem = function(toShow){		
			$(o.item_selector,this).removeClass("tab_open").addClass("tab_closed");
			$(o.content_selector,this).css('display','none');
			$(toShow).addClass("tab_open").removeClass("tab_closed");			
			this.displayHolder.html($(o.content_selector,toShow).html());
		} 
		$(o.item_selector,selfref).each(function(i){
			var me	= this;
			$(o.link_selector, this).click(function(){selfref.showItem(me);});
		;});
		
		selfref.showItem($(o.item_selector,selfref)[0]);
    }); 	
 };   
})(jQuery);

function popup(popuptype,identifier,clicked){
	clicked.href='javascript:void(0)';
	if(popuptype==1){
		// type 1 = zoom image
		var w = dhtmlwindow.open('popupbox_zoom', 'ajax', identifier, undefined, 'width=628px,height=660px,center=1,resize=0,scrolling=0');	
		$('.drag-contentarea',w).css({'height':'auto','overflow':'auto'});		
	}else if(popuptype == 2){
		//type 2 = special offer, write/read review
		var w = dhtmlwindow.open('popupbox_'+identifier, 'div', identifier, undefined, 'width=628px,height=600px,center=1,resize=0,scrolling=0');			
		$('.popup_heading h1, .product_preview .ItemName', w).sifr({path:'/images/',font:'Gill_Sans_MT_Light',textAlign: 'left' });
		$('h1.products, .email_a_friend .ItemName',w).sifr({path:'/images/',font:'Gill_Sans_MT_Light_nospace',textAlign: 'left' });
		$(' .product_preview .ItemBrand, .email_a_friend .ItemBrand',w).sifr({path:'/images/',font:'Gill_Sans_MT',textAlign: 'left' });
		$('.drag-contentarea',w).css({'height':'auto','overflow':'auto'});	
		
		
	}else if(popuptype == 3){
		//type 3 = product preview
		var w = dhtmlwindow.open('popupbox_product', 'ajax', identifier, undefined, 'width=628px,height=660px,center=1,resize=0,scrolling=0');
		//dhtmlwindow code has been modified to add the sifr functions when the ajax has loaded
		
		$('.drag-contentarea',w).css({'height':'auto','overflow':'auto'});
	}
	
	return false;
	
}


function showHideDiv(divID){
	// This function is for design preview only to simulate pop-ups in the header (login form and cart summary)
	// developers to replace with suitable script to handle AXAJ functionality	
	$('#'+divID).toggle();
}

function openSubNav(clicked,openClass){
	clicked.href='javascript:void(0)';
	var p=$(clicked.parentNode);
	var isOpen =$(clicked.parentNode).hasClass(openClass);
	p.siblings("."+openClass).removeClass(openClass);
	if(isOpen){
		p.removeClass(openClass);
	}else{
		p.addClass(openClass);
	}
	return false;
}

function bookmark(clicked){
var b = $.browser;
var url = window.location.href;
var title = document.title;
  if (b.mozilla){   
    window.sidebar.addPanel(title, url, "");
  }else if(window.opera && window.print){ // opera  
   clicked.href = url;
   clicked.title = title;
   clicked.rel = 'sidebar';
	return true;	
  }else if(b.msie){// ie
    window.external.AddFavorite(url, title);
  }else{
	 alert('This browser only supports manual bookmarking');
  }
  return false;
}


$(document).ready(function() {
    $(document).pngFix();
    //$('#overlay').bind("click",function(){dhtmlwindow.closeallopenwindows();});
    $('.CatalogueListing, .SearchListing, .CrossSell .Related_Products, .CrossSell_HomepageFeature .Related_Products').tabulate();
    $('.Incentives .Related_Products').tabulate({ table_width: 576, cell_width: 144 });
    $('.home_heading, .CrossSell_HomepageFeature .CrossSell_heading, h1.blog_heading ').sifr({ path: '/images/', font: 'Gill_Sans_MT_Light', textAlign: 'left' });
    $('h1.catalogue_heading, .flashtext,  .CrossSell .CrossSell_heading, .cart_heading h1,  .column_main div.ProductDescription .ItemBrand, .advanced_search h1.ResultHeading, .QuickOrder h1, .InfoPage h1').sifr({path:'/images/',font:'Gill_Sans_MT_Light_nospace',textAlign: 'left' });
    $('.column_main div.ProductDescription .ItemName').sifr({path:'/images/',font:'Gill_Sans_MT',textAlign: 'left' });
    $('.AdditionalInfoTextHtml').make_tabs();
    $('.advanced_search_results').make_tabs({ item_selector: '.result_type', link_selector: '.result_heading', content_selector: '.result_content' });
    $('.SiteMap').tabulate({ cell_selector: '.sitemap_catalogue' });
})
