var COOKIE_NAME = 'RNoffer';
var opts = { path: '/', expires: 10 };
var requiredFields = '';

var l = document.location;
		
//form vars
var uName = '';
var uCompany = '';
var uAddress = '';
var uTel = '';
var uEmail = '';
var vars = new Object;

var resp = '';
var eStatus = '';

var jssCart = '';

//var vars = new Array();
var els = new Array();

var forgotPassHTML = '<span class="font08em"><p>Please enter your email address and click submit to retrieve your login details.</p><input class="login" type="text" name="uEmail" id="uEmail" onblur="uEmail=this.value"><br><input type="submit" value="submit" id="requestLogin"></span>';
var $dialog = $('<div></div>');
var uEmail = $('#uEmail').val();


function resetForm(){

	$('#productBrand :nth-child(1)').attr('selected', 'selected');
	$('#colour :nth-child(1)').attr('selected', 'selected');
	$('#design :nth-child(1)').attr('selected', 'selected');
	$('#style :nth-child(1)').attr('selected', 'selected');
	$('#newCollections :nth-child(1)').attr('selected', 'selected');
	$('#gender :nth-child(1)').attr('selected', 'selected');
	
}

function findProducts(method){
	//alert('findProducts');
	//alert('findPlants');
	var number = 40;
	
	if(method=='next'){
		var start = Number($('#start').html())+number;
	}else if(method=='previous'){
		var start = Number($('#start').html())-number;
	}else{
		var start = Number($('#start').html());
	}
	if(start<0){
		start = 0;
	}
	var end = start+number;
	
	$('#preLoader').css('display','');
	
	var jssCart = encodeURIComponent($('#jssCart').val());
	var productType = encodeURIComponent($('#productType').val());
	var productBrand = encodeURIComponent($('#productBrand').val());
	var colour = encodeURIComponent($('#colour').val());
	var design = encodeURIComponent($('#design').val());
	var style = encodeURIComponent($('#style').val());
	var newCollections = encodeURIComponent($('#newCollections').val());
	var gender = encodeURIComponent($('#gender').val());
	var code = encodeURIComponent($('#code').val());
	var order = encodeURIComponent($('#order').val());
	
	if(style=='Childrens'){
		$('.gender').css({'display':'inline'});
	}else{
		$('.gender').css({'display':'none'});
	}
	
	var args = '?productType='+productType+'&productBrand='+productBrand+'&colour='+colour+'&design='+design+'&style='+style+'&newCollections='+newCollections+'&code='+code+'&order='+order+'&jssCart='+jssCart+'&start='+start+'&number='+number+'&gender='+gender;

	//set url location hash
	document.location = l.protocol + "//" + l.hostname + "/product_finder#find"+args;
	
	//alert(getUrlVars()['productType']);
	
	//check if hash exists in url//
	if(window.location.hash){
		//get url vars and set form values#]
		$('#jssCart').val(decodeURIComponent(getUrlVars()['jssCart']));
		$('#productType').val(decodeURIComponent(getUrlVars()['productType']));
		$('#productBrand').val(decodeURIComponent(getUrlVars()['productBrand']));
		$('#colour').val(decodeURIComponent(getUrlVars()['colour']));
		$('#design').val(decodeURIComponent(getUrlVars()['design']));
		$('#style').val(decodeURIComponent(getUrlVars()['style']));
		$('#newCollections').val(decodeURIComponent(getUrlVars()['newCollections']));
		$('#gender').val(decodeURIComponent(getUrlVars()['gender']));
		$('#code').val(decodeURIComponent(getUrlVars()['code']));
		$('#order').val(decodeURIComponent(getUrlVars()['order']));
	}
	
	
	
	//$('#preLoader').css('display','block');
	
	var target = l.protocol + "//" + l.hostname + "/ajaxProductFinder.php"+args;
	
	
	//prompt("",target);
	
	$.ajax({
			type: "GET",
			url: target,
			dataType: 'xml',
			cache: false,
			success: function(xml){				
				var num = ($(xml).find('products').attr('totalProducts'));
				//alert(num);
				var jssCart = $(xml).find('jssCart').text();
				
				$('#results').html('');
				$('#start').html('');
				$('#end').html('');
				$('#productNum').html('');
				
				var newHTML = "";
				var c = 1;

				if(num>0){
				
				$(xml).find('product').each(function(){
													 
						linkSrc = $(this).find('linkSrc').text();
						prodID = $(this).find('prodID').text();
						imgSrc = $(this).find('imgSrc').text();
						bgColour = $(this).find('bgColour').text();
						productName = $(this).find('productName').text();
						offerFlash = $(this).find('offerFlash').text();
						shortdescription = $(this).find('shortdescription').text();
						productPrice = $(this).find('productPrice').text();
						prodRRP = $(this).find('prodRRP').text();
						
						if(bgColour!=""){
									
								
						newHTML += '<div class="brushPanel" onmouseover="showSwatch(this,\''+productName+'\',\''+bgColour+'\')">';
							newHTML += '<div class="brushHolder" style="background:'+bgColour+';">';
							newHTML += '<a href="'+linkSrc+'"><img src="images/img_brush.png" alt="Fired Earth Sissinghurst White" title="'+productName+'" width="106" height="108"></a>';
							newHTML += '</div>';
							newHTML += '<h2 class="font075em"><strong><span class="purple">'+shortdescription+'</span></strong></h2>';
							newHTML += '<h2 class="font075em"><strong><span class="purple">'+productName+'</span></strong></h2>';
                   
						newHTML += '</div>';
				
					}else{
						newHTML += '<div class="itemBrief" onclick="document.location='+linkSrc+'" onmouseover="showPreview(this,'+productName+','+imgSrc+', \'';
						
						if (c%5==0) { }else{ newHTML += ' left';};
						newHTML += '\', '+offerFlash+')">';
						
							if(offerFlash!=""){

								newHTML += '<div class="offerFlash dropShadow">'+offerFlash+'</div>';
							}
								newHTML += '<div align="center" style="width:120px; height:100px; text-align:center; display:table-cell; vertical-align:middle;" >';
									
								newHTML += '<a href="'+linkSrc+'?brand=">';
								
								
								newHTML += '<img src="'+imgSrc+'" alt="'+productName+'" title="'+productName+'"/></a><br/>';
								
								
								newHTML += '</div>';
								 
								newHTML += '<strong><span class="font075em"><span class="purple">'+productName+'<br />'+shortdescription+'</span></span><br/></strong>';
								
								if(prodRRP!="0" && prodRRP!="0.00"){

									newHTML += '<span style="font-size:12px;">Now </span>';
								}
								newHTML += '<span style="font-size:22px;">'+productPrice+'</span><br/>';

								if(prodRRP!="0" && prodRRP!="0.00"){

									newHTML += '<span class="red" style="font-size:12px;">Was<span class="strike"> &pound;'+prodRRP+'</span></span><br/>';
					
								}
								var saving = prodRRP-productPrice;
								if(prodRRP!="0" && prodRRP!="0.00"){
									newHTML += '<span class="brightgreen" style="font-size:12px;">Save &pound;'+saving+'</span><br/>';
								}
								newHTML += '<strong><span class="font075em"><a href="'+linkSrc+'?brand=" class="purple">View Details &gt;</a></span></strong>';
							newHTML += '</div>';
					}		
						c++;
				});
				}else{
					newHTML += '<p style="text-align:center; padding:20px;" class="brown">Sorry, no products were found<br/>Please change your criteria try again</p>';
				}
				//alert(newHTML);
				$('#preLoader').css('display','none');
				if(num<2){var numText = 'Product has been found';}
				if(num>1){var numText = 'Products have been found';}
				$('#start').html(start);
				$('#end').html(end);
				$('#productNum').html(num);
				$('#results').html(newHTML);
				
			}
			
		});
	
	
	
}


$(document).ready(function(){
	
	
	
	
	//Show the paging and activate its first link
	$(".paging").show();
	$(".paging a:first").addClass("active");
	//On Click
	$(".paging a").click(function() {
		$active = $(this); //Activate the clicked paging
		//Reset Timer
		clearInterval(play); //Stop the rotation
		rotate(); //Trigger rotation immediately
		rotateSwitch(); // Resume rotation timer
		return false; //Prevent browser jump to link anchor
	});
	
	//Get size of the image, how many images there are, then determin the size of the image reel.
	if($(".window").length>0){
		var imageWidth = $(".window").width();
	}else{
		var imageWidth = $(".window_pr").width();
	}
	var imageSum = $(".image_reel img").size();
	var imageReelWidth = imageWidth * imageSum;
	
	//Adjust the image reel to its new size
	$(".image_reel").css({'width' : imageReelWidth});
	
	//Paging  and Slider Function
	rotate = function(){
		var triggerID = $active.attr("rel") - 1; //Get number of times to slide
		displayAnnotation($active.attr("rel"));
		var image_reelPosition = triggerID * imageWidth; //Determines the distance the image reel needs to slide
	
		$(".image_reel a").removeClass('active'); //Remove all active class
		$active.addClass('active'); //Add active class (the $active is declared in the rotateSwitch function)
	
		//Slider Animation
		$(".image_reel").animate({
			left: -image_reelPosition
		}, 500 );
	
	};
	//Show annotation
	function displayAnnotation(num){
		$('.annotation').animate({
			opacity:0
		}, 200, function(){
			$('.annotation').css({'display':'none'});
			$('#annotation_'+num).css({'display':'block'});
			$('#annotation_'+num).animate({
				opacity:1
			}, 200);
		});
		
	}
	//Rotation  and Timing Event
	rotateSwitch = function(){
		play = setInterval(function(){ //Set timer - this will repeat itself every 7 seconds
			$active = $('.image_reel a.active').next(); //Move to the next paging
			if ( $active.length === 0) { //If paging reaches the end...
				$active = $('.image_reel a:first'); //go back to first
			}
			rotate(); //Trigger the paging and slider function
		}, 3000); //Timer speed in milliseconds (7 seconds)
	};
	//rotateSwitch(); //Run function on launch
	
    $('.slideshow').cycle({
		fx: 'fade' // choose your transition type, ex: fade, scrollUp, shuffle, etc...
	});
	
	var carousels = new Array();
    //Create the carousels
    $('[class~="carousel"]').each(function(){
        carousels.push(new Carousel($(this)));
    });
	
	//Check if a shipping method is selected
	var xShippingSelect = $('input[name="xShippingSelect"]:checked').length;
	if(xShippingSelect<=0){
		$('#3').attr('checked','checked');
		$('#shippingChange').submit();
	}
	
	$('.retry').live('click', function(){
		$dialog.html(forgotPassHTML);
	});
	//alert('DOM ready');
	$dialog.html(forgotPassHTML);
		$dialog.dialog({ 
			dialogClass: 'login-dialog',
			autoOpen: false,
			title: 'Request login details',
			resizable: false
		});
		//getter
		var dialogClass = $dialog.dialog( "option", "dialogClass" );
		//setter
		
		$('.forgotPass').click(function() {
			$dialog.dialog('open');
			$dialog.dialog( "option", "dialogClass", 'login-dialog' );
		});
		
		$('#requestLogin').click(function(){
        	
            if(!uEmail || uEmail==''){
				//alert(uEmail);
            	alert('Please enter your email address that you have registered with us');
            }else{
				
				var args = '?uEmail='+uEmail+'&fSent=requestPass';
				//prompt('',"ajaxFormProcessor.php"+args);
                $.ajax({ 
                    url: "ajaxFormProcessor.php"+args, 
                    dataType: 'xml',  
                    success: function(xml){
                        var resp;
                        $(xml).find('message').each(function(){
                            resp = $(this).find('response').text();
                        });
                        $dialog.html(resp);
                }});
            }
		});
	
	$(".categoryText").hide();
	
	$(".linkImage").css("opacity", 0.4);
	
	$(".linkImage").mouseover(function() {
		$(this).css("opacity", 1);
	});
	
	$(".linkImage").mouseout(function() {
		$(this).css("opacity", 0.4);
	});
	
	$(".linkTitle").mouseover(function() {
		$(this).parent().find(".linkImage").css("opacity", 1);
	});
	
	$(".linkTitle").mouseout(function() {
		$(this).parent().find(".linkImage").css("opacity", 0.4);
	});
	
	$(".toggle").mouseover(function () {
		$(this).css('cursor', 'pointer');
	});
	
	$(".toggle").click(function(){								
		var parentTable = $(this).parents('table');
		parentTable.find('.categoryText').slideToggle();					 
	});
	
	$("#offerYes").click(function(){
   		$("#discounts").show();
		$.cookie(COOKIE_NAME, 'yes', opts);
		//alert($.cookie("RNoffer"));
   	});
	
	$("#offerNo").click(function(){
   		$("#discounts").hide();
		$.cookie(COOKIE_NAME, 'no', opts);
		//alert($.cookie("RNoffer"));
	});

    $("#compBtn").click(function(){
    	submitForm('competition','response');
     });
	
	function checkCookie(){
		if($.cookie("RNoffer")=='yes'){
			$("#offerYes").attr("checked", "checked");
			$("#discounts").show();
		}else{
			$("#offerNo").attr("checked", "checked");
			$("#discounts").hide();
		}
	}
	
	checkCookie();

	//alert($.cookie(COOKIE_NAME));
	
	function getOptions(){
		
			var args = '?finish='+finish+'&prodID='+prodID;
			
			$.ajax({
				type: "GET",
				url: "ajax_io.php"+args,
				dataType: 'xml',
				success: function(xml){
					var messages = ($(xml).find('message').length);
					
					//alert(messages);
					$(xml).find('message').each(function(){
														 
							eStatus = $(this).find('eStatus').text();
							//alert(eStatus);
							resp = $(this).find('response').text();
							//alert(response);
							//prompt('',$(this).find('sql').text());
							//prompt('',$(this).find('query').text());
					});
					
					$('#'+responseDiv).html(resp);
					
					if(eStatus!='fail'){
						$('#'+responseDiv).css('color','green');
						$('#customerLogin').submit();
						$('#'+formID).siblings('.loginBtn').css('display','none');
						$('#'+formID).css('display','none');
					}else{
						$('#'+responseDiv).css('color','red');
						$('#'+formID).siblings('.loginBtn').css('display','inline');
						$('#'+formID).css('display','inline');
					}
				}
				
			});
	}
	
	$("#professionalSubmit").live('click',function(){
        //handleEnquiryRequest();
		//vars = [uName, uEmail, uTel, uEnquiry];
		//els = ['.uName', '.uEmail', '.uTel', '.uEnquiry'];
		submitForm('valuationForm', 'enquiryForm');
    });
	
	$('#offerBtn').live('click',function(){
		submitForm('discountsForm', 'response');
    });
	
	$("#loginBtn").live('click',function(){
        //alert('login');
		//vars = [''+uEmail+'', ''+uPassword+''];
		//alert('vars');
		//els = ['.uEmail', '.uPassword'];
		//alert('els');
		submitForm('customerLogin', 'response');
    });

	fName = $('#fName').val();

	function setVars(formID){
		//alert($("#"+formID+' #uName').val());
		fEmail = $("#"+formID+' #fEmail').val();
		fSent = $("#"+formID+' #fSent').val();
		uPassword = $("#"+formID+' #uPassword').val();
		
		uAnswer = $("#"+formID+' #uAnswer').val();
		uName = $("#"+formID+' #uName').val();
		uCompany = $("#"+formID+' #uCompany').val();
		uAddress = $("#"+formID+' #uAddress').val();
		uTel = $("#"+formID+' #uTel').val();
		uEmail = $("#"+formID+' #uEmail').val();
		
		xjssCart = $("#"+formID+' #xjssCart').val();
		xOfferCode = $("#"+formID+' #xOfferCode').val();
		isDiscount = $("#"+formID+' #isDiscount').val();
	} 
	
	function submitForm(formID, responseDiv){	
			
		//alert(formID);
		
		setVars(formID);
		
		if(checkRequired(formID)==true){
			
			var args = '?fEmail='+fEmail+'&uPassword='+uPassword+'&fSent='+fSent+'&uName='+uName+'&uCompany='+uCompany+'&uAddress='+uAddress+'&uTel='+uTel+'&uEmail='+uEmail+'&uAnswer='+uAnswer+'&xjssCart='+xjssCart+'&xOfferCode='+xOfferCode+'&isDiscount='+isDiscount;
			
			//document.location = 'phpScripts/form_processor.php'+args;
			//prompt("","/ajaxFormProcessor.php"+args);
			
			$('#'+responseDiv).html('Processing <img src="images/ajax-loader.gif" />');
			
			$.ajax({
				type: "GET",
				url: "ajaxFormProcessor.php"+args,
				dataType: 'xml',
				success: function(xml){
					//var messages = ($(xml).find('quiz').length);
					
					//alert(messages);
					$(xml).find('message').each(function(){
														 
							eStatus = $(this).find('eStatus').text();
							//alert(eStatus);
							resp = $(this).find('response').text();
							//alert(response);
							//prompt('',$(this).find('sql').text());
							//prompt('',$(this).find('query').text());
					});
					
					$('#'+responseDiv).html(resp);
					
					if(eStatus!='fail'){
						$('#'+responseDiv).css('color','green');
						$('#'+formID).submit();
						$('#'+formID).siblings('.loginBtn').css('display','none');
						$('#'+formID).css('display','none');
					}else{
						$('#'+responseDiv).css('color','red');
						$('#'+formID).siblings('.loginBtn').css('display','inline');
						$('#'+formID).css('display','inline');
					}
				}
				
			});
	
		}
		
	}
	
	
	
	function checkRequired(formID){
		var checkRequired = true;
		
		var requiredFields = $('#'+formID).find('.required');
		//alert(requiredFields.length);
		
		var message = 'Please fill in all required fields\n(Highlighted in Red)\n\n';
	
		for(i=0; i<requiredFields.length; i++){
			//alert(requiredFields[i].id+' : '+requiredFields[i].value);
			if(requiredFields[i].value==""){
				$('#'+formID).find('.'+requiredFields[i].id).css('color','red');
				//alert($('#'+formID).find('.'+requiredFields[i].id).text());
				message += $('#'+formID).find('.'+requiredFields[i].id).text()+'\n';
				checkRequired = false;
			}else{
				$('.'+requiredFields[i].id).css('color','#909191');
			}
			
		}
			
		if(checkRequired==false){
			alert(message);
		}
		
		return checkRequired;
	}

});

function getSample(formID){
	$("#options option:contains('0.250l')").attr("selected", "selected");
	$("#options option:contains('0.125l')").attr("selected", "selected");
	$("#options option:contains('0.06l')").attr("selected", "selected");
	$("#options option:contains('Sample')").attr("selected", "selected");
	//alert($("#options option:contains('0.125l')").text());
	$('#'+formID).submit();
}

function setOption(prodID){
	var finish = $("#selectFinish").val();
	var size = $("#selectSize").val();
	
	var val = new String(finish+size);
	selectOptionByValue('options', val);
	recalcPrice(prodID);
}

function selectOptionByValue(selObj, val){
    var A= document.getElementById(selObj).options, L= A.length;
    while(L){
		
		var y = A[--L].text;
		var x = val;
//		alert(y);
//		alert(x);
        if (y==x){
//			alert('match');
//			alert(selObj);
//			if(document.getElementById(selObj)){
//				alert('selObj Found');
//			}
            document.getElementById(selObj).selectedIndex = L;
            L= 0;
        }
    }
}

function getSizes(prodID){
	var finish = $("#selectFinish").val();
//	alert(finish);
//	alert(finishes[finish].length);
	
	$('#selectSize').find('option').remove();
	
	var option = document.createElement("option");

	for(i=0;i<finishes[finish].length;i++){
		//alert(finishes[finish][i]);
		addOption('selectSize', finishes[finish][i], finishes[finish][i]);
	}
	setOption(prodID);
}

function addOption(el, name, value){
//		alert("Element:"+el+" name:"+name+" value:"+value);
		try{
		 getElement(el).add(new Option(name, value), null) //add new option to end of "sample"
		}
		catch(e){ //in IE, try the below version instead of add()
		 getElement(el).add(new Option(name, value)) //add new option to end of "sample"
		}
}

function getElement(el){
	return document.getElementById(el);
}

function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    return vars;
}

