// JavaScript Document
var timerCookie;
var continueShoppingLink = "",baskettempsmall = 0,baskettemplarge = 0;
dataid = new Array();
total_temp_large = new Array();
total_temp_small = new Array();

dataid[99] = 0; // standard
dataid[400] = 0; // 3 pack
dataid[401] = 0; // 6 pack

dataid[100] = 0; // large
dataid[396] = 0; // 3 pack
dataid[397] = 0; // 6 pack



var topBannersOFF = [
	['t-facebook-may.jpg','http://www.thecaliforniacompany.co.uk/Sale-Shutters-and-Blinds/']
];

var topBanners = [
	['t-easyinstallation.jpg','http://www.thecaliforniacompany.co.uk/Shutters/'],
	['t-pricepromise.jpg','http://www.thecaliforniacompany.co.uk/Customer-Services/Price-promise/'],
	['t-quality.jpg','http://www.thecaliforniacompany.co.uk/Shutters/'],
	['t-heretohelp.jpg','http://www.thecaliforniacompany.co.uk/Shutters/'],
	['t-bespokeshutters.jpg','http://www.thecaliforniacompany.co.uk/Shutters/']
];

var bottomBannersOFF = [

	['b-facebook-valentine.jpg','http://www.thecaliforniacompany.co.uk/Sale-Shutters-and-Blinds/'],
	['b-temporaryblinds.jpg','http://www.thecaliforniacompany.co.uk/Temporary-Blinds/']
	['b-sale-spring.jpg','http://www.thecaliforniacompany.co.uk/Sale-Shutters-and-Blinds/'],

];
var bottomBanners = [
	['b-spendandsave.jpg','http://www.thecaliforniacompany.co.uk/Sale-Shutters-and-Blinds/'],
	['b-facebook-generic.jpg','http://www.thecaliforniacompany.co.uk/Sale-Shutters-and-Blinds/'],
	['b-blindsfreedelivery.jpg','http://www.thecaliforniacompany.co.uk/Sale-Shutters-and-Blinds/'],
	['b-price-promise.gif','http://www.thecaliforniacompany.co.uk/Customer-Services/Price-promise/'],
	['b-temporaryblinds.jpg','http://www.thecaliforniacompany.co.uk/Temporary-Blinds/']
];

function openContactUs(){
	$('openContactUs').style.display = "none";
	$('closeContactUs').style.display = "";
	new Effect.BlindDown($('contactustrans'));
}
function closeContactUs(){
	$('closeContactUs').style.display = "none";
	$('openContactUs').style.display = "";
	new Effect.BlindUp($('contactustrans'));
}

function openAreasCovered(){
	$('openAreasCovered').style.display = "none";
	$('closeAreasCovered').style.display = "";
	new Effect.BlindDown($('areascoveredtrans'));
}
function closeAreasCovered(){
	$('closeAreasCovered').style.display = "none";
	$('openAreasCovered').style.display = "";
	new Effect.BlindUp($('areascoveredtrans'));
}
function featureOver(id,pos){
	id.style.backgroundPosition = pos;
	id.style.cursor = "pointer";
}
function featureOut(id,pos){
	id.style.backgroundPosition = pos;
	id.style.cursor = "";
}
function featureClick(id){
	link = $(id).down('a');
	if(link != undefined) {
		location.href = link.href;
	}
}
function headermenu(item){
	if($(item)){
		$(item).addClassName('header-menu-on');
	}
}
function continueShoppingB(cSLink){
	switch (cSLink) {
		case 'doors':
			$('moredoors').show();
		break;
		case 'blinds':
			$('moreblinds').show();
		break;
		case 'shutters':
			$('moreshutters').show();
		break;
	}
}
function additem(itemid){

	quty = $('quantity'+itemid).value;

	new Ajax.Request('/modules/shop/add.php', {
	  method: 'get',
	  parameters: {dataid: itemid, orderquantity: quty},
	  onSuccess: cartchanged
	  });

}
function onLoad() {
	// this doesn't help, Opera is currently broken:
	if (window.opera && window.history) {
		history.navigationMode = 'compatible';
	}
	// Set-up the polling:
	timerCookie = window.setTimeout(onTick, 200);
}
function onUnload() {
	if (timerCookie) {
		window.clearTimeout(timerCookie);
	}
}
function cartchanged(transport){
	$('products_cartnote').style.display = "";
	setTimeout("$('products_cartnote').style.display = 'none';", 2000 );
}
function galleryZoom(id) {
	imagebox = "gallery_image_"+id;
	imagelink = $(imagebox).select('a');
	popUp(imagelink[0].href,300,400);
//	eval("page" + id + " = window.open('" + imagelink[0].href + "', 'page" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width=300,height=400');");
//	window.location.href = imagelink[0].href;
}

function temporder(width) {

	tempsmall = 0;

	templarge = Math.floor(width / 1210);

	widthleft = width - (templarge * 1210);

	if(widthleft < 910) {
		tempsmall = 1;
	}
	else {
		templarge = templarge + 1;
	}
	baskettempsmall += tempsmall;
	baskettemplarge += templarge;
}

/* OLD CODE
function tempExtraOrder() {
	
	baskettempsmall = baskettempsmall - dataid[99];
	baskettemplarge = baskettemplarge - dataid[100];
	
	if(baskettempsmall > 0 || baskettemplarge > 0) {
		$('extraTemps').style.display = "";
		extraTempsTotal = 0;
		if(baskettempsmall > 0)	{
			extraTempsTotal = baskettempsmall * 5;
		}
		if(baskettemplarge > 0)	{
			extraTempsTotal = extraTempsTotal + (baskettemplarge * 8);
		}
		$('extraTempsPrice').innerHTML = extraTempsTotal;
	}


}*/

function tempExtraOrder() {
	// this works out the number of blinds in the order, and how many more needs to be added.
	baskettempsmall = baskettempsmall - dataid[99];
	baskettempsmall = baskettempsmall - dataid[400] * 3;
	baskettempsmall = baskettempsmall - dataid[401] * 6;
	baskettemplarge = baskettemplarge - dataid[100];
	baskettemplarge = baskettemplarge - dataid[396] * 3;
	baskettemplarge = baskettemplarge - dataid[397] * 6;
		
	total_temp_large = return_packs(baskettemplarge); // get the total needed from the function
	total_temp_small = return_packs(baskettempsmall);

	if(baskettempsmall > 0 || baskettemplarge > 0) {
		$('extraTemps').style.display = "";
		extraTempsTotal = 0;
	
		// prices are hard coded.
		extraTempsTotal += total_temp_large['1_pck'] * 8;
		extraTempsTotal += total_temp_large['3_pck'] * 20.95;
		extraTempsTotal += total_temp_large['6_pck'] * 39.95;
		
		extraTempsTotal += total_temp_small['1_pck'] * 6;
		extraTempsTotal += total_temp_small['3_pck'] * 16.95;
		extraTempsTotal += total_temp_small['6_pck'] * 30.95;
		/*if(baskettempsmall > 0)	{
			extraTempsTotal = baskettempsmall * 5;
		}
		if(baskettemplarge > 0)	{
			extraTempsTotal = extraTempsTotal + (baskettemplarge * 8);
		}*/
		
		$('extraTempsPrice').innerHTML = extraTempsTotal.toFixed(2);
	}


}

function return_packs(temp_num){
	/*
		this function returns an array with the number of single, 3 pack and 6 pack blinds required.
	*/
	var mod_six = 0;
	var whole_six =0;
	var mod_three = 0;
	var whole_three = 0;
	var whole_one = 0;
	

	if(temp_num >=3){ // check to see if more the 3 blinds are needed
		if(temp_num >=6){ // if it's greater then 6
			mod_six = temp_num % 6; // work out the remainder 
			whole_six = Math.floor(temp_num / 6); // the total number of 6 packs
			if(mod_six >=3){ // if the remainder is greater or equal 3
				mod_three = temp_num % 3; // the remainder of 3 pck
				whole_three = Math.floor(temp_num / 3); // the total num of 3 packs
				whole_one = mod_three; // the total number of 1 packs
			}else{
				whole_one = mod_six; 
				
			}
		
		}else{ // no six packs needed
			mod_three = temp_num % 3;
			whole_three = Math.floor(temp_num / 3);
			whole_one = mod_three;
		}
	}else{ // if not then we only want single packs
		whole_one = temp_num;
	}

	var arr = new Array();
	arr['1_pck'] = whole_one;
	arr['3_pck'] = whole_three;
	arr['6_pck'] = whole_six;
	return arr; // return the array.
}

function getDataQuantity(basid) {
	if($('quantity['+basid+']')) {
		return $('quantity['+basid+']').value;
	}
}

function tempExtraOrderAdd() {

	if(total_temp_small['1_pck'] > 0)	{
		new Ajax.Request('/modules/shop/add.php', {method: 'get', parameters: {dataid: 99, orderquantity: total_temp_small['1_pck']}});
	}
	if(total_temp_small['3_pck'] > 0)	{
		new Ajax.Request('/modules/shop/add.php', {method: 'get', parameters: {dataid: 400, orderquantity: total_temp_small['3_pck']}});
	}
	if(total_temp_small['6_pck'] > 0)	{
		new Ajax.Request('/modules/shop/add.php', {method: 'get', parameters: {dataid: 401, orderquantity: total_temp_small['6_pck']}});
	}
	if(total_temp_large['1_pck'] > 0)	{
		new Ajax.Request('/modules/shop/add.php', {method: 'get', parameters: {dataid: 100, orderquantity: total_temp_large['1_pck']}});
	}
	if(total_temp_large['3_pck'] > 0)	{
		new Ajax.Request('/modules/shop/add.php', {method: 'get', parameters: {dataid: 396, orderquantity: total_temp_large['3_pck']}});
	}
	if(total_temp_large['6_pck'] > 0)	{
		new Ajax.Request('/modules/shop/add.php', {method: 'get', parameters: {dataid: 397, orderquantity: total_temp_large['6_pck']}});
	}
	
	setTimeout("window.location = '/Basket/'", 1000 )
}

// cookie handling
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
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);
}

// maxmind expander and collapser - prototype
function maxmindExpand(){
	new Effect.SlideDown('maxmindWrapper', { duration: 0.5 });
}
function maxmindCollapse(){
	new Effect.SlideUp('maxmindWrapper', { duration: 0.5 });
}
function maxmind_showDiv(data) {
	if (data == 'US' && (readCookie('shutt_maxmind') == null)) {
		$('maxmind').innerHTML = '<div id="maxmindWrapper"><div id="maxmindWrapper_i"><a href="http://www.theshutterstore.com/" title="Window shutters USA"><img src="/sitestyle/templates/images/USA-flag.jpg" width="43" height="43" alt="USA flag" /></a><p class="maxmindText"><span class="maxmindTitle">Looking for window shutters from USA?</span><br />Click here to visit <a href="http://www.theshutterstore.com/" title="Window shutters USA">The Shutter Store - our USA partners</a> or <span id="maxmindButtonClose" class="like-a-link">click here to close this notice</span></p></div></div>';
		$('maxmindWrapper').hide();
		$('maxmindWrapper').appear({ duration: 2.0 });
		$('maxmindButtonClose').observe('click', function(event){if(this == event.target){maxmindCollapse();createCookie('shutt_maxmind', 'US', 30);}});
	}
}
function maxmind_getMaxmindGeoCountry() {
	new Ajax.Request('/sitestyle/lib/class.maxmind.php', {
		method: 'post',
		parameters: {x: 1},
		onSuccess: function(response) { maxmind_showDiv(response.responseText); }
	});
}
document.observe("dom:loaded", function() {
//	maxmind_getMaxmindGeoCountry();
	iPadTest();
});

function setupProductTab() {
	addLoadEvent(moveDetails);
	changeProductTab('description');
}
function moveDetails() {
	$('right-column').insert({ top: $('detailview') });
	$('detailview').show();
}

var readMoreRaady = false;

function changeProductTab(id) {
	$$('.tab').each(function(value, index) { value.removeClassName('on');});
	$$('.tabarea').each(function(value, index) { value.hide();});
	
	$('tab_'+id).addClassName('on');
	$('area_'+id).show();
	
	if(id == 'reviews' && !readMoreRaady){
		readMoreSetup();
	}
}

// Read more
function readMoreSetup(){
	$$('.apost .text').each(function(value, index) {
			if(value.getHeight() > 58){
				value.addClassName('short');
				value.insert({ after: '<a class="moretext" onClick="readMoreOpen(this);">read more...</a>' });
			}
		}
	);
	
}
function readMoreOpen(id){
	id.previous().removeClassName('short');
	id.replace('<a class="moretext" onClick="readMoreClose(this);">close</a>');
}
function readMoreClose(id){
	id.previous().addClassName('short');
	id.replace('<a class="moretext" onClick="readMoreOpen(this);">read more...</a>');
}

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

function iPadTest(){
	var isiPad = navigator.userAgent.match(/iPad/i) != null;
	if(isiPad){
		$('installation').style.position = 'absolute';
		$('installation').style.left = '-3px';
		$('installation').style.right = 'auto';
		$('installation').style.top = '196px';
	}
}


var Slideshow = Class.create({
	initialize: function(id, delay, speed, items, action) {
		this.id = id;
		this.delay = delay;
		this.speed = speed;
		this.totalElmt = items.length;
		this.action = action;
		
		this.paused = 0;
		this.arrSlideElmt = [this.totalElmt];
		this.curElmtNum = 0
		this.forward = 1;
		this.curEffect1;
		this.curEffect2;
				
		block = '';
		//preload all elements into array and preload all images within element
		for (i = 0; i < this.totalElmt; i++) {
		
			this.arrSlideElmt[i] = new Element('a', { href: items[i][1] });
			if(i != 0){
				this.arrSlideElmt[i].hide();
			}
			this.arrSlideElmt[i].insert({ top: new Element('img', {src: '/sitestyle/templates/images/homebanners/'+items[i][0]}) });

			$(id+'banners').insert({ top: this.arrSlideElmt[i] });
			this.arrSlideElmt[i].observe('mouseover', function() { this.paused = 0;this.pause(); }.bind(this));  //pause on mouseover
			this.arrSlideElmt[i].observe('mouseout', function() { this.paused = 1;this.pause(); }.bind(this));  //resume on mouseout
			
			$$(this.arrSlideElmt[i].img).each(function(img) {	
				img = new Image();
			});
		}
		$$('.'+id+'_controls .right').each(function(node) {
			node.observe('click', function(s){
				this.arrSlideElmt[this.curElmtNum].setStyle({ display: 'none' });
				this.checkSlide();
				if(this.curEffect1){
					this.curEffect1.cancel();
				}
				if(this.curEffect2){
					this.curEffect2.cancel();
				}
				this.arrSlideElmt[this.curElmtNum].setStyle({ display: 'block', left: '0px' });
				$$('.'+this.id+'_controls .pause').each(function(node) {
					node.setStyle({backgroundPosition:'0px -377px'});
				});
				this.paused = 1;
			}.bind(this));
		}.bind(this));
		$$('.'+id+'_controls .left').each(function(node) {
			node.observe('click', function(s){
				this.arrSlideElmt[this.curElmtNum].setStyle({ display: 'none' });
				this.forward = 0;
				this.checkSlide();
				if(this.curEffect1){
					this.curEffect1.cancel();
				}
				if(this.curEffect2){
					this.curEffect2.cancel();
				}
				this.arrSlideElmt[this.curElmtNum].setStyle({ display: 'block', left: '1px' });
				this.forward = 1;
				$$('.'+this.id+'_controls .pause').each(function(node) {
					node.setStyle({backgroundPosition:'0px -377px'});
				});
				this.paused = 1;
			}.bind(this));
		}.bind(this));
		$$('.'+id+'_controls .pause').each(function(node) {
			node.observe('click', function(s){
				this.pause();
			}.bind(this));
		}.bind(this));
	},
	start: function() {
		if(this.totalElmt > 1){
			this.executor = new PeriodicalExecuter(function() {
				this.next(); //start slidehow
			}.bind(this), this.delay);
		}
	},
	
	next: function(){
		if (!this.paused) {
			this.update();
		}
	},
	pause: function(){
		if(this.paused == 1){
			this.paused = 0;
			$$('.'+this.id+'_controls .pause').each(function(node) {
				node.setStyle({backgroundPosition:'0px -358px'});
			});
		}
		else {
			this.paused = 1
			$$('.'+this.id+'_controls .pause').each(function(node) {
				node.setStyle({backgroundPosition:'0px -377px'});
			});
		}
	},
	update: function() {
		if(this.action == 'slide'){
			current = this.curElmtNum;
			width = this.arrSlideElmt[this.curElmtNum].getWidth();
			this.checkSlide();
			this.arrSlideElmt[this.curElmtNum].setStyle({left:width+'px'});
			this.arrSlideElmt[this.curElmtNum].show();
			
			this.curEffect1 = new Effect.Move(this.arrSlideElmt[current], { x: '-'+width, y: 0, mode: 'absolute', transition: Effect.Transitions.sinoidal, duration: this.speed, fps: 100 });	
			this.curEffect2 = new Effect.Move(this.arrSlideElmt[this.curElmtNum], { x: 0, y: 0, mode: 'absolute', transition: Effect.Transitions.sinoidal, duration: this.speed, fps: 100 });	
		}
		else {
			new Effect.Fade(this.arrSlideElmt[this.curElmtNum], { duration: this.speed });
			this.checkSlide();
			new Effect.Appear(this.arrSlideElmt[this.curElmtNum], { duration: this.speed });
		}



//		new Effect.Fade(this.arrSlideElmt[this.curElmtNum],{afterFinish:function(){
//			this.checkSlide();
//			new Effect.Appear(this.arrSlideElmt[this.curElmtNum]);
//		}.bind(this)});
	},
	checkSlide: function() {
		if(this.forward == 1){
			this.curElmtNum ++;
		}
		else {
			this.curElmtNum --;
		}
		if (this.curElmtNum == (this.totalElmt)) { this.curElmtNum = 0; }
		if (this.curElmtNum == -1) { this.curElmtNum = this.totalElmt -1; }
	}
});

function setupColourHover() {
	$('site-copyright').insert({'after': new Element('div', {'id':'hover_outer'})});
	$('hover_outer').hide();
	$(document).observe('mousemove', function(e) {
		_x = Event.pointerX(e)+10;
		_y = Event.pointerY(e)-160;

		$('hover_outer').setStyle({
			'left':_x+'px',
			'top':_y+'px'
		});
	});
}

function captureColourHover(id) {
	$$(id).invoke('observe', 'mouseover', function() {
			$('hover_outer').innerHTML = '<span class="'+this.className+'"></span>';
			$('hover_outer').show();
	}).invoke('observe', 'mouseout', function() {
//		$('hover_outer').innerHTML = '';
		$('hover_outer').hide();
	});
}

