/* basket functions */
var basket;
var basketwindow;
var infowindow;
var ajaxWait = '<table><tr><td><img src="images/ajax-loader-small.gif" alt="" /></td><td>Loading, please wait...</td></tr></table>';

function showPopUpWindow(Name, File, w, h, Status, Resize, Scroll) {
	var t=0, l = 0, winstring = "";

	if(infowindow) {
		if(!infowindow.closed) {
			infowindow.close();
		}
	}

	l = (screen.width / 2) - (w / 2);
	t = (screen.height / 2) - (h / 2);

	winstring = "width=" + w + ", height=" + h + ",left=" + l + ",top=" + t +  ",status=" + Status + ",resizable=" + Resize + ",scrollbars=" + Scroll;

	infowindow = window.open(File,Name,winstring);
	infowindow.focus();

	return;
}


function isEmail(email) {
	var invalidCharString = " ,<>!\"?%^&*()+=*/\\\';:#~[]{}";
	var i = 0;
	
	for (i = 0; i < invalidCharString.length; i++) {
		if (-1 < email.indexOf(invalidCharString.charAt(i))) {
			return false;
		}
	}
	
	var firstAt = email.indexOf('@');
	var lastAt = email.lastIndexOf('@');
	var lastDot = email.lastIndexOf('.');
	if (!((0 < firstAt) && (1 < lastDot) && (firstAt == lastAt) && ((firstAt + 1) < lastDot) && (lastDot < (email.length - 2)))) 
	{
		return false;
	}
	else {
		return true;
	}
}

function ShowBasket()
{
	var t, l, winstring;

	if(basketwindow) {
		if(!basketwindow.closed) { basketwindow.close(); }
	}

	l = (screen.width / 2) - (635 / 2);
	t = (screen.height / 2) - (480 / 2);

	winstring = "width=635, height=480,left=" + l + ",top=" + t +  ",status=yes,resizable=no,scrollbars=yes";

	basketwindow = window.open(basehref+'viewbasket.htm','basket',winstring);
	basketwindow.focus();

	return;
}

function bigpiclink(picID, w, h, newWin){
	BigPicLink(picID, w, h, newWin);
}

function BigPicLink(picID, w, h, newWin){
	// if( newWin ){
		ShowPopUpWindow("BigPic",basehref+"bigpic.cfm?pic_id="+picID,w,h,"no","no","yes");
	// }
	// else{
//		document.location.href = 'popup_pic.cfm?pic_id=' + picID;
//	}
}

function OpenInPopup(url)
{
	showPopUpWindow("prpopup",basehref + url,870,650,"yes","yes","yes");
}


function getRadioButtonValue(radioButtonArray) {
	var value = '', i = 0;
	
	if (!radioButtonArray.length) {
		// Only one radio button, so form.radiobuttonname returns a radiobutton element, not an array
		if (radioButtonArray.checked) {
			value = radioButtonArray.value;
		}
	}
	else {
		for (i=0; i<radioButtonArray.length; i++) {
			if (radioButtonArray[i].checked) {
				value = radioButtonArray[i].value;
				break;
			}
		}
	}
	
	return value;
}


/* View basket scripts */

function ShowTermsPopUp(Name, File, w, h, Status, Resize, Scroll) {
	var t=0, l = 0, winstring = "";
	var infowindow;

	if(infowindow) {
		if(!infowindow.closed) { infowindow.close(); }
	}

	l = (screen.width / 2) - (w / 2);
	t = (screen.height / 2) - (h / 2);

	winstring = "width=" + w + ", height=" + h + ",left=" + l + ",top=" + t +  ",status=" + Status + ",resizable=" + Resize + ",scrollbars=" + Scroll;

	infowindow = window.open(File,Name,winstring);

	return;
}

function viewTerms() {
	ShowTermsPopUp('Terms', basehref +  'terms.cfm', 670, 450, 'yes', 'no', 'yes');
}

function Checkout(count)
{
	var msg = "";

	// update();
	// document.frmBasket.SList.value = basket;

	msg += UpSell_Validate(document.frmBasket);

	if ( msg === "" ) {
		if (document.frmBasket.ShipCountry.selectedIndex === 0) {
			msg += "Please select a Country/Region";
		}
		if (msg === "" ) {
			if( flgQuickOrder ) {
				document.frmBasket.action = securebasehref + "default.cfm/loadfile.BuyConf.cfm";
			}
			else {
				document.frmBasket.action = securebasehref + "default.cfm/loadfile.BuyBasket.cfm";
			}
			
			document.frmBasket.submit();
		}
		else {
			alert(msg);
		}
	}
	else {
		alert(msg);
	}
}
/* End of viewbasket scripts */

function update()
{
	var count = $('#txtBasketCount').val();
	var n = 0;
	
	clearbasket();
	
	for(n = 0; n < count; n++)
	{
		if(qty[n]>0)
		{
			add2order(id[n],qty[n],col[n],descrip[n]);
		}
	}
}

function ClearBasket()
{

	if(confirm("Your Basket will be emptied."))
	{
		clearbasket();
		document.location.href = document.location.href;
	}
}

function applyoffercode()
{
	if(document.getElementById('txtOfferCode').value != '')
	{
		recalculate(1);
	}
	else
	{
		alert('Please enter an offer code.');
	}
}

function recalculate(count)
{
	var basketForm = document.getElementById("frmBasket");
	basketForm.submit();
}

function remove(code)
{
	if(confirm("The item will be removed from your basket."))
	{
		var basketForm = document.getElementById("frmBasket");
		var itemId = '';
		
		$('#txtItemToRemove').val(code);
		
		basketForm.submit();
	}
}

function OpenViewBasket()
{
	var url = basehref + 'ViewBasket.htm';

//	if( pageIndex > 0 ) {
	//	url += '/PreviousPage.' + pageIndex;
	// }
		
	document.location.href = url;
}

function RefreshBasket(Fin_Price)
{
	if(document.getElementById("Price"))
	{
		document.getElementById("Price").innerText = 'Fin_Price';
	}
}

function refreshViewBasket()
{
	if(basketwindow) {
		basketwindow.document.location.href = basketwindow.document.location.href;
	}

	return;
}

function clearbasket() {
	updateHeadingBasketTotal(0, 0);
}

function updateHeadingBasketTotal(numItems, totalAmount) {
	if( numItems == 0 ) {
		numItems = 'No Items';
	}

	$('#headerBasketItems').html(numItems);
	totalAmount = parseFloat(totalAmount);

	$('#headerBasketAmount').html(totalAmount.toFixed(2));
}

function SubmitItem()
{
	var frm = document.frmQty;
	var qty = parseInt(frm.qty.options[frm.qty.selectedIndex].text, 10)
	var gridPricingId = $('#txtGridPricingID').val();
	var description = $('#txtDescription').val();
	var col = $('#ddlColour').val();
	var duoCol = $('#ddlDuoSelect').val();
	var msg = '';

	if( col === -1 || col === 'NoCol' ){
		msg += '\n* Please select a colour!';
	}
		
	if( $('#ddlDuoSelect').is(':visible') && duoCol == -1 ) {
		msg += '\n* Please selct a duo colour!';
	}
		
	if(isNaN(qty) || qty < 0){
		msg == '\n* Quantity Must be a positive whole number';
	}
	else if( qty == 0 )
	{
		if(confirm("You have entered a quantity of 0, the item will not be added to your basket.")){
			$('#dlgAddToBasket').dialog('close');
		}
		return;
	}
	
	$('.qtyXSell').each(function(){
		if( $(this).val() > 0 ){
			var $parent = $(this).parent().parent();
			var xSellDescription = $parent.find('.txtDescriptionXSell').val();
			
			if( $parent.find('.ddlColourXSell').val() === 'NoCol' ){
				msg += '\n* Please select a colour for: ' + xSellDescription;
			}
		}
	});
	
	$('.ddlColourXSell').each(function(){
		if( $(this).val() !== 'NoCol' ){
			var $parent = $(this).parent().parent();
			var xSellDescription = $parent.find('.txtDescriptionXSell').val();
			var xSellColour = $parent.find('.ddlColourXSell option:selected').text();
			
			if( $parent.find('.qtyXSell').val() === '0' ){
				msg += '\n* Please select a quantity for ' + xSellColour + '/' + xSellDescription;
			}
		}
	});
	
	if( msg != '' ) {
		alert(msg);
		return;
	}
	
	var id = $('#txtProductPriceId').val();
	var desc = $('#txtGridPricingID').val();

	if( $('#ddlDuoSelect').is(':visible')  ){
		 col = col + '/' + duoCol;
	}
	
	if( basket != '') {
		basket += ':';
	}
	basket += id + ',' + qty + ',' + col + ','+ desc;
	
	url = 'BasketConfirmPopup.cfm?change=false&id=' + id + '&qty=' + qty + "&colour=" + col + '&desc=' + desc;
	
	var postData = $('#frmQty').serialize();
	
	$.post(url, postData, function(data) {
		$('#dlgAddToBasket').html(data);
	});	
}

function AddToBasket(GridPricingID)
{
	var url = basketbasehref + 'AddToBasketPopup.cfm?gridpricingid=' + GridPricingID;
	
	$('#dlgAddToBasket').dialog('open');
	$('#dlgAddToBasket').html(ajaxWait);
	
	$.post(url, function(data) {
		$('#dlgAddToBasket').html(data);
	});
}

function OpenQtyPopup(id,PriceGridID,bloadindex)	
{
	AddToBasket(id,PriceGridID,bloadindex);
}
/* end of basket functions */


var dlgAddToBasketDialogOptions = {
    autoOpen: false,
    bgiframe: true,
    modal: true,
    resizable: false,
    width: 725,
    height: 'auto', // 380,
	open: function () {
                        $(this).parents(".ui-dialog:first").find("#dlgAddToBasket").addClass('.addToBasketDialogClass .ui-dialog.ui-dialog-content.addToBasketDialogClass2');
                    },
    maxHeight: 500,
	dialogClass: 'addToBasketDialogClass'
};

function dlgAddToBasketDialogOptions_Clicked() {

}

function NoneLink() {
	return;
}

function ShowPopUpWindow(Name, File, w, h, Status, Resize, Scroll) {
	var t=0, l = 0, winstring = "";

	if(infowindow) {
		if(!infowindow.closed) infowindow.close()
	}

	l = ((screen.width / 2) - (w / 2))
	t = ((screen.height / 2) - (h / 2))

	winstring = "width=" + w + ", height=" + h + ",left=" + l + ",top=" + t +  ",status=" + Status + ",resizable=" + Resize + ",scrollbars=" + Scroll;

	infowindow = window.open(File,Name,winstring);
	infowindow.focus();

	return;
}


function loadImg(path,id) {
	var strImgName = 'swatchImg_'+ id

	document.getElementById(strImgName).src = path;
}

function openMenu_Click() {

		$("div#panel").animate({
			height: "550px" 
		})
		.animate({
			height: "510px" 
		}, "fast");
		
		$("div.panel_button").toggle();
		
		$(".panel_bot").css("background-image", "url(graphics/bot-curve.png)");
		
		return false;
	
}

/* Video Report Dialog */
var dialogOptions = { width: 650, height: 500 }
var ajax = null;

function Ajax()
{
	this.toString = function() {return "Ajax";}
	this.makeRequest = function(_method, _url, _callbackMethod)
	{
		this.request = (window.XMLHttpRequest)? new XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP");
		this.request.onreadystatechange = _callbackMethod;
		this.request.open(_method, _url, true);
		this.request.send(_url);
		this.request.contenttype = "text/html"
		this.request.charset = "ISO-8859-1"

	}
	this.checkReadyState = function(_id, waitContent, showMessage, suppressWaitContent)
	{
		return this.request.status;
	}
}

function loadVideo_Complete(data)
{
	if( ajax.request.readyState == 4 && ajax.request.status == 200 )
	{
		var waitMessage = document.getElementById('VideoReportLoading');
		var videoReport = document.getElementById('VideoReport');
		
		waitMessage.style.display = 'none';
		videoReport.style.display = 'block';
		
		videoReport.innerHTML = ajax.request.responseText;
		
		$('#VideoReportDialog').center();

	}
}

function VideoReport(videoId)
{
	ShowVideoReport(videoId);
}

function RequestQuote(rdoEnquiryType){

	var t=0, l = 0, winstring = "";


	if(infowindow){
		if(!infowindow.closed) infowindow.close()
	}
	l = ((screen.width / 2) - (595 / 2))
	t = ((screen.height / 2) - (535 / 2))
	winstring = "width=592,height=535,left=" + l + ",top=" + t +  ",status=yes,resizable=no,scrollbars=yes";
	
	var url = basehref + 'QuoteRequest.cfm';

	if( rdoEnquiryType ) {
		url += '?EnquiryType=' + rdoEnquiryType;
	}
	
	infowindow = window.open(url, 'PersonalisedQuote', winstring);

	return;
}

function ShowVideoReport(videoId)
{
	var dlg = document.getElementById('VideoReportDialog');
	var dialogShield = document.getElementById('dialogShield');
	var closeButton = document.getElementById('CloseButton');
	
	var btns = document.getElementById('VideoDialogButtons');
	var title = document.getElementById('VideoDialogTitle');
	
	var videoReport = document.getElementById('VideoReport');
	var waitMessage = document.getElementById('VideoReportLoading');
	
	dlg.style.display = 'block';
	waitMessage.style.display = 'block';
	videoReport.style.display = 'block';

	closeButton.onclick = function(){
		dialogShield.style.display = 'none';
		dlg.style.display = 'none';
		
		return false;
	}
	
	dlg.style.width = dialogOptions.width;
	dlg.style.height = dialogOptions.height;
	
	dlg.style.top = ((getPageHeight() / 2) - (dialogOptions.height / 2)) + getScrollTop();
	dlg.style.left = (getPageWidth() / 2) - (dialogOptions.width / 2);
	
	var videoHeight = dialogOptions.height - (btns.offsetHeight + title.offsetHeight);
	
	videoReport.style.height = videoHeight;
	videoReport.style.minHeight = videoHeight;
	
	dialogShield.style.display = 'block';
	dialogShield.style.height = getDocHeight();
	dialogShield.style.width = getDocWidth();
	
	btns.style.width = dialogOptions.width;
	
	$('#VideoReportDialog').center();
	
	var url = 'ShowVideoReport.cfm?id=' + videoId;
	
	ajax = new Ajax();
	ajax.makeRequest('get', url, loadVideo_Complete);
}


function getScrollTop()
{
	var ScrollTop = document.body.scrollTop;
	 
	if (ScrollTop == 0)
	{
		if (window.pageYOffset)
			ScrollTop = window.pageYOffset;
		else
			ScrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
	}
	
	return ScrollTop;
}

function bigpiclink(picID, w, h, newWin){
	BigPicLink(picID, w, h, newWin);
}

function BigPicLink(picID, w, h, newWin){
	ShowPopUpWindow("BigPic",basehref+"bigpic.cfm?pic_id="+picID,w,h,"no","no","yes");
}

function getScrollLeft()
{
	var scrollLeft = document.body.scrollLeft;
	 
	if (scrollLeft == 0)
	{
		if (window.pageXOffset)
			scrollLeft = window.pageXOffset;
		else
			scrollLeft = (document.body.parentElement) ? document.body.parentElement.scrollLeft : 0;
	}
	
	return scrollLeft;
}


function getDocHeight(){ 
	if( document.height != undefined ) // good browsers
	{	
		return document.height;
	}
	else{
		var scrollHeight = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
		var offsetHeight = Math.max(document.documentElement.offsetHeight, document.body.offsetHeight);

		return scrollHeight < offsetHeight ? offsetHeight :  scrollHeight;
	}
}

function getDocWidth(){ 

	if (document.width != undefined) // good browsers
	{
		return document.width;
	}
	else{
		var scrollWidth = Math.max(document.documentElement.scrollWidth, document.body.scrollWidth);
		var offsetWidth = Math.max(document.documentElement.offsetWidth, document.body.offsetWidth);

		return scrollWidth < offsetWidth ? offsetWidth : scrollWidth;
	}
}

function getPageWidth()
{
	if( document.all ){ 
		var clientWidth = document.documentElement.clientWidth;
		
		if( clientWidth <= 0 ) clientWidth = document.body.clientWidth;
	
		return clientWidth; 
	} 
	else { 
		return window.innerWidth; 
	}
}

function qtychange(el,i)
{
	var q = parseInt(el.options[el.selectedIndex].value);

	qty[i] = q;
//	el.value= q;
	return true;
}

function getPageHeight()
{
	if( document.all ){ 
		var clientHeight = document.documentElement.clientHeight;
		
		if( clientHeight <= 0 ) clientHeight = document.body.clientHeight;
		
		return clientHeight; 
	} 
	else { 
		return window.innerHeight; 
	} 
}

window.onresize = function()
{
	var dialogShield = document.getElementById('dialogShield');
	
	if( dialogShield )
	{
		dialogShield.style.height = getDocHeight();
		dialogShield.style.width = getDocWidth();
	}
}

function showSlingshot(){
	$('#divClickToOpenMenu').fadeIn(2000, function(){
		setTimeout("$('#divClickToOpenMenu').fadeOut(2000);", 5000);
	 });
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function getRoundedNum(precision) {
			var power = Math.pow(10, precision || 0);
			return String(Math.round(this * power)/power);
}

$(document).ready(function() {
	$("div.panel_button").click(openMenu_Click);
	
	$("div#hide_button").click(function() {
		$("div#panel").animate({
			height: "0px"
		}, "fast", function() {
			$(".panel_bot").css("background-image", "") });
		
		return false;
	});	
	
	var large3dCarousel = {			
		xPos: 460,
		yPos: 60,
		mouseWheel: false,
		altBox: $("#alt-text"),
		titleBox: $("#title-text"),
		FPS:30,
		autoRotate: 'left',
		autoRotateDelay: 5000,
		speed:0.2,
		bringToFront:true,
		yRadius: -50,
		xRadius: 360,
		loadingDiv: $('.divCarouselLoading')
	};
			
	var smallFlatCarousel = {
		xPos: 245,
		yPos: 40,
		buttonLeft: $("#left-but"),
		buttonRight: $("#right-but"),
		altBox: $("#alt-text"),
		titleBox: $("#title-text"),
		mouseWheel: false,
		FPS: 30,  
		autoRotate: 'left',
		autoRotateDelay: 5000,
		speed: 0.2,
		bringToFront:true,
		yRadius: -30,
		xRadius: 140,
		loadingDiv: $('.divCarouselLoading')
	};
				
				
	$(".carouselSmall").css('width', '490px');
	$(".carouselSmall").css('height', '250px');

	if( typeof $(".carouselSmall").CloudCarousel != 'undefined' ) {
		$(".carouselSmall").CloudCarousel(smallFlatCarousel);
	}

	if( typeof $(".carouselLarge").CloudCarousel != 'undefined' ) {
		$(".carouselLarge").CloudCarousel(large3dCarousel);
	}
	
	$('.priceHeadingGroup').children('.silverheader').click(function() {
		$(this).next('.submenu').slideToggle();
		return false;
	});
	
	 if (typeof jQuery.ui !== 'undefined') {
			$('#dlgAddToBasket').dialog(dlgAddToBasketDialogOptions);
	}

	 $('.languageHover').hover(function() {
		var imgPath = $(this).children('img').attr('src');
		imgPath = imgPath.replace(/\.gif/, '-glow.gif');
		$(this).children('img').attr('src', imgPath);
	 },
	 function() {
		var imgPath = $(this).children('img').attr('src');
		imgPath = imgPath.replace(/\-glow\.gif/, '.gif');
		$(this).children('img').attr('src', imgPath);
	 });
	 
	jQuery.fn.center = function () {
		var topPos = (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop();
		var leftPos = (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft();
		
		if( topPos < 0 ) {
			topPos = 0;
		}

		if( topPos < $(window).scrollTop() ) {
			topPos = $(window).scrollTop();
		}

		this.css("position","absolute");
		this.css("top", topPos + "px");
		this.css("left", leftPos + "px");
		
		return this;
	}

	if (!Number.prototype.toFixed) {
		Number.prototype.toFixed = function(precision) {
			var power = Math.pow(10, precision || 0);
			return String(Math.round(this * power)/power);
		}
	}
	
	setTimeout("showSlingshot()", 1000);
});

