
/**
 * BCS Comments
 ***************************************
 * <jQuery.fn.createSlideViewport>
 *
 * Description : jQuery.fn.createSlideViewport is a jQuery plugin for creating a slide grid.
 ****************************************/
jQuery.fn.createSlideViewport=function(options){
	// default setting
	var defaults={
		count:3,
		duration:500,
		data:[],
		index:0,
		currentY:0,
		offsetY:250,
		viewportCls:"viewportCls",
		viewportCellCls:"viewportCellCls",
		viewportBgCls:"viewportBgCls",
		viewportBgCls2:"viewportBgCls2",
		saveWidgetCls:"saveWidgetCls",
		formatFunction:function(n){
			return dollarAmount(n);
		}
	};
	
	options=jQuery.extend(defaults,options);
	options.total=Math.ceil(options.data.length/options.count);
	
	function createProductCell(p){
		var cellCls=options.viewportBgCls2;
		var el= "<li class='"+cellCls+"'><div class='"+options.viewportCellCls+"'><div><img src='"+p.imageSrc+"' alt=''/></div>";
		el+="<h3><a href='"+p.productURL+"'>"+p.productTitle+"</a></h3>";
		el+="<h4><label>CODE:</label>"+p.productCode+"</h4>";
		if(p.productOurPrice){
			el+="<em>"+options.formatFunction(p.productOurPrice)+"</em>";
		}
		if(p.productListPrice>0){
			el+="<h4><label>List Price:</label>"+options.formatFunction(p.productListPrice)+"</h4>";
		}
		if(p.productOurPrice){
			
			var saved=Math.round(100*(p.productListPrice-p.productOurPrice)/p.productListPrice);
	
			if(saved>0&&saved<Infinity){
				el+="<h4><label>You Save:</label>"+options.formatFunction(p.productListPrice-p.productOurPrice)+"</h4>";
				el+="<div class='"+options.saveWidgetCls+"'>"+(saved+"%")+"</div>";
			}
		}
		el+="</div></li>";
		return el;
	}

	function createProductRow(p){
		var el="<div class='"+options.viewportCls+"'><ul>";
		for(var i=0;i<p.length;i++){
			el+=createProductCell(p[i]);
		}
		el+="</ul></div>";
		return el;
	}

	function getRawDataAt(n){
		if(n<0){
			n=0;
		}else if(n>=options.total){
			n=options.total-1;
		}
		var result=[];
		for(var i=n*options.count,j=0;j<options.count;i++,j++){
			if(options.data[i]){
				result.push(options.data[i]);
			}
		}
		return result;
	}
	
	//@return
	return this.each(function(index){
		$content=jQuery(this);
		$content.css("position","relative").css("float","left");
		var html="";
		for(var i=0;i<options.total;i++){
			html+=createProductRow(getRawDataAt(i));
		}
		$content.append(html);
		if(jQuery.browser.msie&&jQuery.fn.pngfix){
			jQuery("."+options.saveWidgetCls).pngfix();
		}

		options.index=0;
		$content.bind("slideNext",function(){
			if($content.sliding==true||options.index==options.total-1){
				return;
			}
			options.currentY-=options.offsetY;
			options.index++;
			$content.sliding=true;
			$content.animate({top:options.currentY},options.duration,function(){
				$content.sliding=false;
				$content.trigger("change");
				if(options.index==options.total-1){
					$content.trigger("slideEnd");
				}
			});
		}).bind("slidePrev",function(){
			if($content.sliding==true||options.index==0){
				return;
			}
			options.currentY+=options.offsetY;
			options.index--;
			$content.sliding=true;
			$content.animate({top:options.currentY},options.duration,function(){
				$content.sliding=false;
				$content.trigger("change");
				if(options.index==0){
					$content.trigger("slideHome");
				}
			});
		});

		$content.find("li").hover(function(){
			$(this).removeClass(options.viewportBgCls2).addClass(options.viewportBgCls);
		},function(){
			$(this).removeClass(options.viewportBgCls).addClass(options.viewportBgCls2);
		}).click(function(){
			document.location=$(this).find("a").attr("href");
		}).css("cursor","pointer");
	});
	// end return
}


/**
 * BCS Comments
 **********************************************
 * Class Name : jQuery.ProductDetailTable
 * Descrption : create a table to show product detail
 *
 **********************************************/
 jQuery.ProductDetailTable=function(ele,options){
	this.el=jQuery(ele);
	this.tbody=this.el.find("tbody")||this.el;
	this.options=jQuery.extend({oddCls:"tableOdd",evenCls:"tableEven",firstTdCls:"tableFirstTd",secondTdCls:"secondTdCls"},options);
 }
 jQuery.extend(jQuery.ProductDetailTable.prototype,{
	addRow:function(name,value){
		this.tbody.append($("<tr><td class='"+this.options.firstTdCls+"'>"+name+"</td><td class='"+this.options.secondTdCls+"'>"+value+"</td></tr>"));
		return this.update();
	},
	removeRowAt:function(n){
		this.tbody.find("tr:eq("+n+")").remove();
		return this.update();
	},
	removeAll:function(){
		this.tbody.empty();
		return this;
	},
	update:function(){
		jQuery("tr:odd",this.tbody).removeClass(this.options.evenCls).addClass(this.options.oddCls);
		jQuery("tr:even",this.tbody).removeClass(this.options.oddCls).addClass(this.options.evenCls);
		var trs=this.tbody.find("tr");
		jQuery("td:eq(0)",trs).addClass("firstTdCls");
		jQuery("td:eq(1)",trs).addClass("secondTdCls");
		return this;
	},
	update2:function(){
		jQuery("tr:odd",this.tbody).removeClass(this.options.evenCls).addClass(this.options.oddCls);
		jQuery("tr:even",this.tbody).removeClass(this.options.oddCls).addClass(this.options.evenCls);
		var trs=this.tbody.find("tr");
		jQuery("td:eq(0)",trs).addClass("firstTdCls2");
		jQuery("td:eq(1)",trs).addClass("secondTdCls");
		return this;
	},
	update3:function(){
		jQuery("tr:odd",this.tbody).removeClass(this.options.evenCls).addClass(this.options.oddCls);
		jQuery("tr:even",this.tbody).removeClass(this.options.oddCls).addClass(this.options.evenCls);
		var trs=this.tbody.find("tr");
		jQuery("td:eq(0)",trs).addClass("firstTdCls3");
		jQuery("td:eq(1)",trs).addClass("secondTdCls");
		return this;
	}
});

/**
 * BCS Comments
 **********************************************
 * Class Name : jQuery.EmailUtil
 * Descrption : validate the email format;
 * 
 **********************************************/
 jQuery.FormUtil=function(){
	 return {
		 EmailRegExp:/^([a-z0-9])(([\-.]|[_]+)?([a-z0-9]+))*(@)([a-z0-9])((([-]+)?([a-z0-9]+))?)*((.[a-z0-9]{2,3})?(.[a-z0-9]{2,6}))$/,
		 validateEmail:function(str){
			return jQuery.FormUtil.EmailRegExp.test(str);
		 },
		 validateRequired:function(ele){
			return jQuery.trim(jQuery(ele).val())!="";
		 }
	 }
 }();

////////////////////////////
function checkNum(data) {
    var valid = "0123456789.";  
	var ok=1 ; var checktemp; 
	for(var i = 0; i < data.length; i++) {
        checktemp = "" + data.substring(i, i + 1);
        if (valid.indexOf(checktemp) == " - 1 ") return 0;
    }
    return 1;
}
function dollarAmount(num) {
    Num = String(num);
    dec = Num.indexOf(".");
    end = ((dec > -1) ? "" + Num.substring(dec, Num.length) : ".00 ");
    Num = "" + parseInt(Num);
    var temp1 = "";
    var temp2 = "";
    if (checkNum(Num) == 0) {
        alert("This does not appear to be a valid number.Please try again.");
    } else {
        if (end.length == 2) end += "0 ";
        if (end.length == 1) end += "00 ";
        if (end == "") end += ".00 ";
        var count = 0;
        for (var k = Num.length - 1; k >= 0; k--) {
            var oneChar = Num.charAt(k);
            if (count == 3) {
                temp1 += ",";
                temp1 += oneChar;
                count = 1;
                continue;
            } else {
                temp1 += oneChar;
                count++;
            }
        }
        for (var k = temp1.length - 1; k >= 0; k--) {
            var oneChar = temp1.charAt(k);
            temp2 += oneChar;
        }
        temp2 = "$ " + temp2 + end;
       return temp2;
    }
}

 /**
 * BCS Comments
 ************************
 * Function : Scroll Top 
 * Description : scroll the page to TOP.
 ***********************/
 function goTop(acceleration, time, oldX, oldY) {
    acceleration = acceleration || 0.1;
    time = time || 16;
    var dx = 0;
    var dy = 0;
    var bx = 0;
    var by = 0;
    var wx = 0;
    var wy = 0;
    if (document.documentElement) {
        dx = document.documentElement.scrollLeft || 0;
        dy = document.documentElement.scrollTop || 0;
    }
    if (document.body) {
        bx = document.body.scrollLeft || 0;
        by = document.body.scrollTop || 0;
    }
    var wx = window.scrollX || 0;
    var wy = window.scrollY || 0;
    var x = Math.max(wx, Math.max(bx, dx));
    var y = Math.max(wy, Math.max(by, dy));
	oldX = oldX || x;
	oldY = oldY || y;
    var speed = 1 + acceleration;
	if(oldY != y)return;/* BCS Comments. Description : break the function */
	var newX = Math.floor(oldX / speed);
	var newY = Math.floor(oldY / speed);
    window.scrollTo(newX, newY);
    if (x > 0 || y > 0) {
        var invokeFunction = "goTop(" + acceleration + ", " + time + ", " + newX + ", " + newY + ")";
        window.setTimeout(invokeFunction, time);
    }
}

/**
 * BCS Comments
 *************************************
 * Description : Configuration indicate the const about this page.
 ************************************/
var Configuration={
	Redirect:{
		datasheet:"",
		printPage:"",
		releaseProduct:"",
		sendToFriend:"",
		viewLargerImage:"",
		getQuote:""
	},
	Form:{
		formAction:"",
		emailRequiredTip:"You did not complete all of the required fields or input data is incorrect. ",
		emailFormatTip:"You did not complete all of the required fields or input data is incorrect. ",
		messageRequiredTip:"You did not complete all of the required fields or input data is incorrect. ",
		formSuccessTip:"",
		formFailureTip:""
	},
	currentTab:0,
	currentQTY:1
};
/**
 * BCS Comments
 ****************************************
 * Description : PageView indicate the View in MVC pattern.
 ***************************************/
var PageView={};
function initView(){
	fixUI();
	initUI();
	initEventHandlers();
}

function fixUI(){
	var targetTable=$("table",$("#buttons_line"));
	var viewImage = $("#productDetail center a:eq(0)").attr("href");
	targetTable.html('<tbody><tr><td><div id="product_get_quote"><div style="text-decoration:inherit;">Get Quote Now</div></div></td></tr></tbody>');
	if(viewImage != undefined){/*BCS Comments. Description : judge the product's image. */
		$("#productDetailView a").attr("href",$("#productDetail center a:eq(0)").attr("href"));
		$("#productDetail a img:eq(1)").width(240).height(180);
	}
	else
		$("#productDetailView span").remove();
	var target=$("#product_get_quote");
	
	var clickFun=targetTable.attr("onclick");
	target.click(function(){
		target.attr("onclick",clickFun)
	});

	targetTable.removeAttr("onclick").removeAttr("onmouseover").removeAttr("onmouseout").removeClass("hand");

	if($(".discount").length==1){
		var saved=$(".discount .list-price:eq(0)").html()+"%";/*BCS Comments. Description : change eq(1) to eq(0). */
		$(".saveWidgetBigCls").html(saved).show();
	}
	if(jQuery.browser.msie&&jQuery.fn.pngfix){
		var fixList=".panel-header-bg2-left,.panel-header-bg2-right,.panel-header-bg-left,.panel-header-bg-right,.refresh,";
		fixList+="img,.panel-header-icon1,.panel-header-icon2,.panel-header-icon3,.panel-header-icon1,.saveWidgetCls,.saveWidgetBigCls,#relativeProductViewport,.saveWidgetSmallCls";
		$(fixList).pngfix();
	}
	if($.browser.mozilla){
		
	}
}

function initUI(){
	PageView.getQuoteButton=$("#product_get_quote");
	PageView.formSendButton=$("#pFormSend");
	PageView.formClearButton=$("#pFormClear");
	PageView.topButtons=$(".product-panel-header-right");
	PageView.productQTY=$(".product-qty-input");
	PageView.productQTYIncButton=$(".product_qty_inc");
	PageView.productQTYDesButton=$(".product_qty_des");
	PageView.forHover=$(".for_hover");
	}

function initEventHandlers(){
/**
* BCS Comments
*****************************************
* Description : control hover style
****************************************/
	PageView.forHover.children().hover(
		function(){
		$(this).css("background-position","0 100%");
		},
		function(){
		$(this).css("background-position","0px 0px");
		}
	);
/**
 * BCS Comments
 ************************
 * Function : Top Position
 * Description : set the position of top button.
 ***********************/
	$(window).scroll(function (){
		var top_position = $("#move_top");
		if(top_position == null) return;
		var x = $(document).scrollTop();
		var y = $(window).height() * 0.8;
		var bottom_position = $(".page_row").next(".prodcut-panel-footer1").offset().top;
		if(x > 0){
			if(bottom_position > x + y + 50){
				top_position.css("top",x + y + "px");
			}
			else
				top_position.css("top",bottom_position - 50 + "px");
			$("#move_top").fadeIn("slow");
		}
		else
			$("#move_top").fadeOut("slow");
	});
/**
 * BCS Comments
 *****************************************
 * Description : "Get Quote Now" button
 ****************************************/
	PageView.getQuoteButton.click(function(){

	}).hover(function(){/* BCS Comments. Description : use one picture to show both link and hover */
		$(this).css("background-position","0 100%");
		},
		function(){
		$(this).css("background-position","0px 0px");
		});
/**
 * BCS Comments
 *****************************************
 * Description : Send button
 ****************************************/
	$("#pFriendName,#pFriendEmail,#pYourName,#pYourEmail,#pYourMessage").focus(function(){
		$("#formTip").html("");
	});

	PageView.formSendButton.click(function(){
		var pFriendName=$.trim($("#pFriendName").val());
		var pFriendEmail=$.trim($("#pFriendEmail").val());
		var pYourName=$.trim($("#pYourName").val());
		var pYourEmail=$.trim($("#pYourEmail").val());
		var pYourMessage=$.trim($("#pYourMessage").val());
		var tipDiv=$("#formTip");

		if(pFriendEmail==""){
			tipDiv.html(Configuration.Form.emailRequiredTip);
			return;
		}
		if(pYourMessage==""){
			tipDiv.html(Configuration.Form.messageRequiredTip);
			return;
		}
		if(!$.FormUtil.validateEmail(pFriendEmail)){
			tipDiv.html(Configuration.Form.emailFormatTip);
			return;
		}
		if(pYourEmail!==""&&!$.FormUtil.validateEmail(pYourEmail)){
			tipDiv.html(Configuration.Form.emailFormatTip);
			return;
		}
		tipDiv.html("");
	
		$("#pFriendName").get(0).form.submit()
		
		
	}).hover(function(){/* BCS Comments. Description : use one picture to show both link and hover */
		$(this).css("background-position","0 100%");
		},
		function(){
		$(this).css("background-position","0px 0px");
		});
/**
 * BCS Comments
 *****************************************
 * Description : Clear button
 ****************************************/
	PageView.formClearButton.click(function(){
		$("#pFriendName").val("");
		$("#pFriendEmail").val("");
		$("#pYourName").val("");
		$("#pYourEmail").val("");
		$("#pYourMessage").val("");
	}).hover(function(){/* BCS Comments. Description : use one picture to show both link and hover */
		$(this).css("background-position","0 100%");
		},
		function(){
		$(this).css("background-position","0px 0px");
		});
/**
 * BCS Comments
 *****************************************
 * Description : Top button
 ****************************************/
	PageView.topButtons.click(function(){
		goTop()
	}).hover(function(){
		$(this).addClass("top_button_hover");
	},function(){
		$(this).removeClass("top_button_hover");
	});
/**
 * BCS Comments
 *****************************************
 * Description : QTY input
 ****************************************/
	PageView.productQTY.each(function(index,item){
		$(item).keydown(function(event){
			var keyCode=event.keyCode;
			var case1=keyCode>=48&&keyCode<=57;
			var case2=keyCode>=96&&keyCode<=105;
			var case3=keyCode==8||keyCode==37||keyCode==39;
			if(event.shiftKey)event.preventDefault();/* BCS Comments. Description : prevent shift key */
			if(case3&&$(item).val().length!=1){
				return;
			}
			if($(item).val().length>=8){
				event.preventDefault();
				return;
			}
			if(keyCode==8||case1||case2){
				setTimeout(function(){
					updateQTY(index,$(item).val());
				},50);
				return;
			}
			event.preventDefault();
		});
	});

	function updateQTY(index,num){
		if(num<=1){
			num=1;
			PageView.productQTYDesButton.eq(index).addClass("des-button-disabled").removeClass("des-button-over");
		}else{
			PageView.productQTYDesButton.eq(index).removeClass("des-button-disabled").addClass("des-button-over");
		}
		PageView.productQTY.eq(index).val(num);
	}
	for(var i = 0 ; i < PageView.productQTY.size(); i++){
		updateQTY(i,PageView.productQTY.eq(i).val());
	}
/**
 * BCS Comments
 *****************************************
 * Description : QTY increase
 ****************************************/
	PageView.productQTYIncButton.each(function(index,item){
		$(item).click(function(event){
			var num = parseInt(PageView.productQTY.eq(index).val(),10);/* BCS Comments. Description : prevent octal number */
			if(PageView.productQTY.eq(index).val()>=99999999){
				return;
			}
			num++;
			updateQTY(index,num);
			$("#all_update").find("table").click();
		});
	});
	
/**
 * BCS Comments
 *****************************************
 * Description : QTY decrease
 ****************************************/
	PageView.productQTYDesButton.each(function(index,item){		
		$(item).click(function(event){
			var num = parseInt(PageView.productQTY.eq(index).val(),10);/* BCS Comments. Description : prevent octal number */
			if(PageView.productQTY.eq(index).val()<=1){
				updateQTY(index,num);
				return;
			}
			num--;
			updateQTY(index,num);
			$("#all_update").find("table").click();
		});
	});
}
/**
 * BCS Comments
 *****************************************
 * Description : DOM Ready Event Handler
 * start application at this.
 ****************************************/
$(document).ready(function(){ 
	
	initView();

	/**
	 * BCS Comments
	 *****************************************
	 * Description : Set event handlers for the Related Products Module.
	 ****************************************/

	 
	var viewport=$("<div></div>").appendTo("#relativeProductViewport").createSlideViewport({data:window.RelatedProducts||[],viewportCls:"productViewportCls",viewportCellCls:"productViewportCellCls"});
	viewport.bind("change",function(){
		$("#slidePrevButton").removeClass("slidePrevButtonDisabled");
		$("#slideNextButton").removeClass("slideNextButtonDisabled");
	}).bind("slideHome",function(){
		$("#slidePrevButton").addClass("slidePrevButtonDisabled");
	}).bind("slideEnd",function(){
		$("#slideNextButton").addClass("slideNextButtonDisabled");
	});

	$("#slideNextButton").click(function(){
		viewport.trigger("slideNext");
	}).hover(function(){
		$(this).removeClass("slideNextButtonOut").addClass("slideNextButtonOver");
	},function(){
		$(this).addClass("slideNextButtonOut").removeClass("slideNextButtonOver");
	}).addClass("slideNextButtonOut");
	if(window.RelatedProducts&&RelatedProducts.length<=3){
		$("#slideNextButton").hide();
		$("#slidePrevButton").hide();
	}
	$("#slidePrevButton").click(function(){
		viewport.trigger("slidePrev");
	}).hover(function(){
		$(this).removeClass("slidePrevButtonOut").addClass("slidePrevButtonOver");
	},function(){
		$(this).addClass("slidePrevButtonOut").removeClass("slidePrevButtonOver");
	}).addClass("slidePrevButtonOut").addClass("slidePrevButtonDisabled");
	if(window.RelatedProducts&&RelatedProducts.length==0){
		$("#productRelative").hide();
	}
	/**
	 * BCS Comments
	 *****************************************
	 * Description : Set event handlers for Product Detail menu
	 * <Specifications>
	 * <Available Options>
	 * <Include Items>
	 * <>
	 ****************************************/
	 var currentMenu=null;
	 var currentTable=null;
	 var tabs=[];
	function initializeTabs(){
		updateTabData();
		if($("#productSpecifications").find("tr").length==0){
			$("#specificationsTab").hide();
		}else{
			tabs.push({tab:$("#specificationsTab"),table:$("#productSpecifications")});
		}
		if($("#productOptions").find("tr").length==0){
			$("#optionsTab").hide();
		}else{
			tabs.push({tab:$("#optionsTab"),table:$("#productOptions")});
		}
		if($("#productIncludeitems").find("tr").length==0){
			$("#includeItemTab").hide();
		}else{
			tabs.push({tab:$("#includeItemTab"),table:$("#productIncludeitems")});
		}
		$("#productSpec table").hide();
		if(tabs.length==0){
			$("#productSpec").hide();
		}else{
			for(var i=0;i<tabs.length;i++){
				bindMenuAndTable(tabs[i].tab,tabs[i].table);
			}
			currentMenu=tabs[0].tab.addClass("menu-span-selected");
			currentMenu.parent().addClass("menu-a-selected");
			currentTable=tabs[0].table.show();
		}

	}
	
	function updateTabData(){
		new $.ProductDetailTable("#productSpecifications").update();
		new $.ProductDetailTable("#productOptions").update2();
		new $.ProductDetailTable("#productIncludeitems").update3();
	}
	
	function bindMenuAndTable(menu,table,data){
		menu.click(function(){
			if(currentMenu){
				currentMenu.removeClass("menu-span-selected");
				currentMenu.parent().removeClass("menu-a-selected");
				currentTable.hide();
			}
			currentMenu=$(this).addClass("menu-span-selected");
			currentMenu.parent().addClass("menu-a-selected");
			currentTable=table.show();
		}).hover(function(e){
			if($(this).html()==currentMenu.html()){
				return;
			}
			$(this).addClass("menu-span-selected").parent().addClass("menu-a-selected");
		},function(){
			if($(this).html()==currentMenu.html()){
				return;
			}
			$(this).removeClass("menu-span-selected").parent().removeClass("menu-a-selected");
		});
	}
	initializeTabs();
	//productPropTable.removeRowAt(2);
	
	$(".showAfterLoadComplete").removeClass("showAfterLoadComplete").show();
	
	//add by tyler
	//call printer when click 'Print Page'
	//$("a[href='#2']").attr("onClick","window.print();");
		
	//$("a[href='#2']").click(function(){	

	
});

//print page funtion
function PrdPrint()
{
	BeforePrint();		
	window.print();
	//AfterPrint();
	setTimeout("AfterPrint()",1000);	 
}

var bodyHtml = ""; //before print page html content
function BeforePrint()
{
	 //productSpec			 
	 //save the content of current
	 bodyHtml = window.document.body.innerHTML;
	 
	 //hidden sth not need to print.
	 $("#productSpecifications").attr("style","display:table;");
	 $("#productOptions").attr("style","display:table;");
	 $("#productOptions").before("<h4>  Available Options</h4>");
	 $("#productIncludeitems").attr("style","display:table;");
	 $("#productIncludeitems").before("<h4>  Included Items</h4>");
	 $("#productSend").attr("style","display:none;");	//hidden related products
	 $("#productRelative").attr("style","display:none;");	//hidden send email part
	 $("#productIncludeitems").after("<hr />")	//hidden send email part
	 //border-bottom: 2px solid #EE4B00;
	 $("#productSpecifications").css("border-bottom","2px solid #EE4B00");
	 $("#productIncludeitems").css("border-bottom","2px solid #EE4B00");
	 $("#productOptions").css("border-bottom","2px solid #EE4B00");
	 $("#optionsTab").remove();
	 $("#includeItemTab").remove();
	 $("#productTableWidget1").remove();
	 $("#productTableWidget2").remove();
	 var centralHtml = document.getElementById("central_part_contents").innerHTML; 
	 window.document.body.innerHTML = centralHtml; 	 
}

function AfterPrint()
{
	 //alert("print finished");
	 window.document.body.innerHTML = bodyHtml;
	 location.reload();
}
