var remove = new Array('lang');
var optionsWindow;

/***********************************************************
* Logout
************************************************************/
function logout_check(del){
	var agree=confirm('By logging out, your shopping basket will be lost');
	if (agree) {
		return true;
	} else {
		return false;
	}
}

/***********************************************************
* Pop-up Window
************************************************************/
function showPopup(url,name,options)
{
	if(optionsWindow!=null && !optionsWindow.closed && optionsWindow.location) {
		optionsWindow.location.href = url;	
	} else {
		optionsWindow = window.open(url,name,options);
		if(!optionsWindow.opener) {
			optionsWindow.opener = self;
		}
	}
	
	if(window.focus) {
		optionsWindow.focus();	
	}
}

/***********************************************************
* Form Validation
************************************************************/
var node_text = 3;	// DOM text node-type
var emptyString = new RegExp(/^\s*$/ );

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

function msg(fld, msgtype, messtext, messnumber){
	var dispmessnumber;
	if (emptyString.test(messtext)) 
		dispmessnumber = String.fromCharCode(160);    
	else  
		dispmessnumber = messtext;
	var elem = document.getElementById(fld);
	elem.firstChild.nodeValue = dispmessnumber;
	elem.className=msgtype;
}

var proceed = 2;  

function commonCheck(valfield, infoID)
{
	//alert('Value Field: '+valfield+', Info Field: '+infoID);
	if (!document.getElementById) 
		return true;  // not available on this browser - leave validation to the server
	var elem = document.getElementById(infoID);
	//if (!elem.firstChild) return true;  // not available on this browser 
	//if (elem.firstChild.nodeType != node_text) return true;  // infoID is wrong type of node
	return proceed;
}

function validaterequired(valfield, infoID)
{
  var stat = commonCheck (valfield, infoID);
  if (stat != proceed) return stat;
  
    if (emptyString.test(valfield.value)) {
      msg (infoID, "warning", 'This is a required field', 1);  
      return false;
    }

  msg (infoID, "valid", "*", 3);  
  return true;
}

function validateemail  (valfield, infoID)
{
  var stat = commonCheck (valfield, infoID);
  if (stat != proceed) return stat;

  var tfld = trim(valfield.value);  // value of field with whitespace trimmed off
  var email = new RegExp(/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i);
  if (!email.test(tfld)) {
    msg (infoID, "warning", 'You have entered an invalid e-mail address', 1);
    return false;
  } else {
  	msg (infoID, "valid", "*", 3);
  	return true;
	}
}

function validatenumber (valfield, infoID)
{
	var stat = commonCheck (valfield, infoID);
	if (stat != proceed) return stat;

	var tfld = trim(valfield.value);

	if (emptyString.test(valfield.value)) {
		msg (infoID, "warning", 'This is not a valid number', 1);
		return false
	}

	var numberRE = new RegExp(/^[0-9 ]*$/);
	if (!numberRE.test(tfld)) {
		msg (infoID, "warning", 'This is not a valid number', 1);
		return false;
	}	
	msg (infoID, "valid", "*", 3);
	return true;
}

function validateagreed (valfield, infoID)
{
	var stat = commonCheck (valfield, infoID);
	if (stat != proceed) return stat;

	if (valfield.checked!=true) {
		msg (infoID, "warning", valfield.title, 1);
		return false;
	}	
	msg (infoID, "valid", "*", 3);
	return true;
}
			
function validateOnSubmit(form) {
	var elem;
	var errs=0;
	
	//var infoLinks = getElementsByClassName('required','span', form);
	//for (var i=0; i < infoLinks.length; i++){	
	var infoLinks = $('#'+form.id+' span.required');
	infoLinks.each(function(i) {
		//alert(infoLinks[i].id);
		//infoLinks[i].className = '';
		$(this).innerHTML = '';
	});

	//var dateLinks = getElementsByClassName('date','input', form);
	//for (var i=0; i < dateLinks.length; i++){
	var dateLinks = $('#'+form.id+' input.date');
	dateLinks.each(function(i) {
		//alert('info_'+dateLinks[i].name);
		el = document.getElementById($(this).attr('id'));
		if (!validatedate(el, 'info_'+$(this).attr('name'))) errs +=1;
	});

	//var numberLinks = getElementsByClassName('number','input', form);
	//for (var i=0; i < numberLinks.length; i++){
	var numberLinks = $('#'+form.id+' input.number');
	numberLinks.each(function(i) {
		//alert('info_'+numberLinks[i].name);
		el = document.getElementById($(this).attr('id'));
		if (!validatenumber(el, 'info_'+$(this).attr('name'))) errs +=1;
	});

	//var emailLinks = getElementsByClassName('email','input', form);
	//for (var i=0; i < emailLinks.length; i++){
	var emailLinks = $('#'+form.id+' input.email');
	emailLinks.each(function(i) {
		//alert('info_'+emailLinks[i].name);
		el = document.getElementById($(this).attr('id'));
		if (!validateemail(el, 'info_'+$(this).attr('name'))) errs +=1;
	});

	//var requireLinks = getElementsByClassName('require','input', form);
	//var requireLinks1 = getElementsByClassName('require','textarea', form);
	//for (var i=0; i < requireLinks.length; i++){
	var requireLinks = $('#'+form.id+' input.require');
	requireLinks.each(function(i) {
		//alert(requireLinks[i].id);
		el = document.getElementById($(this).attr('id'));
		if (!validaterequired(el, 'info_'+$(this).attr('name'))) errs +=1;
	});
	
	//for (var i=0; i < requireLinks1.length; i++){
	var requireLinks1 = $('#'+form.id+' textarea.require');
	requireLinks1.each(function(i) {
		//alert('info_'+requireLinks[i].name);
		el = document.getElementById($(this).attr('id'));
		if (!validaterequired(el, 'info_'+$(this).attr('name'))) errs +=1;
	});

	//var agreeLinks = getElementsByClassName('agree','input', form);
	//for (var i=0; i < agreeLinks.length; i++){
	var agreeLinks = $('#'+form.id+' input.agree');
	agreeLinks.each(function(i) {
		//alert('info_'+agreeLinks[i].name);
		el = document.getElementById($(this).attr('id'));
		if (!validateagreed(el, 'info_'+$(this).attr('name'))) errs +=1;
	});


	return (errs==0);
};

/***********************************************************
* Set up the links in the page with their onsubmit handlers
************************************************************/
function preparePage(){
	
	if(document.getElementById('del_same_as_bill')){
		del_same_as_bill = document.getElementById('del_same_as_bill');
		del_same_as_bill.onclick = function(){
			if(del_same_as_bill.checked==true){
				document.getElementById('del_address1').className = '';
				document.getElementById('info_del_address1').className = '';
				document.getElementById('info_del_address1').firstChild.nodeValue = '';
				
				document.getElementById('del_town').className = '';
				document.getElementById('info_del_town').className = '';
				document.getElementById('info_del_town').firstChild.nodeValue = '';
				
				document.getElementById('del_county').className = '';
				document.getElementById('info_del_county').className = '';
				document.getElementById('info_del_county').firstChild.nodeValue = '';
				
				document.getElementById('del_postcode').className = '';
				document.getElementById('info_del_postcode').className = '';
				document.getElementById('info_del_postcode').firstChild.nodeValue = '';
				
				document.getElementById('del_country').className = '';
				document.getElementById('info_del_country').className = '';
				document.getElementById('info_del_country').firstChild.nodeValue = '';
			} else {
				document.getElementById('del_address1').className = 'require';
				document.getElementById('info_del_address1').className = 'required';
				document.getElementById('info_del_address1').firstChild.nodeValue = '*';
				
				document.getElementById('del_town').className = 'require';
				document.getElementById('info_del_town').className = 'required';
				document.getElementById('info_del_town').firstChild.nodeValue = '*';
				
				document.getElementById('del_county').className = 'require';
				document.getElementById('info_del_county').className = 'required';
				document.getElementById('info_del_county').firstChild.nodeValue = '*';
				
				document.getElementById('del_postcode').className = 'require';
				document.getElementById('info_del_postcode').className = 'required';
				document.getElementById('info_del_postcode').firstChild.nodeValue = '*';
				
				document.getElementById('del_country').className = 'require';
				document.getElementById('info_del_country').className = 'required';
				document.getElementById('info_del_country').firstChild.nodeValue = '*';
			}
		}
	}
	
	if(document.getElementById('agree_terms')){
		agree_terms = document.getElementById('agree_terms');
		agree_terms.onclick = function(){
			if(agree_terms.checked==true){
				document.getElementById('info_agree_terms').className = '';
				document.getElementById('info_agree_terms').firstChild.nodeValue = '';
			} else {
				document.getElementById('info_agree_terms').className = 'agree';
				document.getElementById('info_agree_terms').firstChild.nodeValue = '*';
			}
		}
	}
	
	$('form.validate').each(function(i) {
		$(this).bind('submit',function(){	
			return validateOnSubmit(this);
		});
	});
	
	$('a.pop').each(function(i) {
		$('#'+this.id).bind('click',function(){	
			showPopup(this.href+'?pop_up=true','popup','toolbar=no, scrollbars=yes, resizable=yes, menubar=no, width=800, height=600');
			return false;
		});
	});

	$('a.logout').each(function(i) {
		$('#'+this.id).bind('click',function(){	
			return logout_check(this);
		});
	});
	
	/* Notify over cart
	************************************/
	if($('#singular_cart').length > 0){
		setTimeout("$('#singular_cart').animate({ opacity: 0 }, 1000, '', function(){ $('#singular_cart').remove(); });", 2500);
	}
	
	/* Gift Finder
	************************************/
	if($('#price_range').length > 0){
		$('#price_range').bind('change', function(){
			range = $('#price_range').val();
			if($('#recipient').length > 0){
				recipient = $('#recipient').val();
			} else {
				recipient = '';	
			}
			$.get('/recipient_list.php', {'price_range':range, 'recipient':recipient}, function(data){
				$('#recipient_list').html(data);
			});
		});
	}
	
	/* Home Images
	************************************/
	if($('#s3sliderContent').children('li').size()>1){
		$('#s3slider').s3Slider({
		    timeOut: 8000
		});
    }
    
    /* Match height product list li's
	************************************/
	$("ul.product_list li").css('min-height', '0');
	$("ul.product_list li").css('height', 'auto');
	$("ul.product_list").each(function(){
		var childCount = 0;
		var childArray = [];
		$(this).children('li').children('span.product_details').children('span.product_title_container').each(function(){
			childCount++;
			childArray.push($(this));
			if(childCount==3){
				equalHeight(childArray);
				childCount = 0;
				childArray = [];
			}
		});
		if(childCount!=0){
			equalHeight(childArray);
		}
	});
	
	/* Tabs
	************************************/
	$("#tabs .tab:not(:first)").hide();

	//to fix u know who
	$("#tabs .tab:first").show();
	
	$("#tabs ul.links a").click(function(){
		stringref = $(this).attr("href").split('#')[1];
		$("#tabs ul.links li").removeClass('ui-tabs-selected');
		$(this).parent().addClass('ui-tabs-selected');

		$('#tabs .tab:not(#'+stringref+')').hide();

		if ($.browser.msie && $.browser.version.substr(0,3) == "6.0") {
			$('#tabs .tab#' + stringref).show();
		} else {
			//$('#tabs .tab#' + stringref).fadeIn();
			$('#tabs .tab#' + stringref).show();
		}
		
		return false;
	});
	
	
	if($('#product_image a.MagicThumb').length > 0){
		MagicThumb.options = {
			keepThumbnail: true,
			zoomPosition: 'center'
		}
	}

}

function equalHeight(group) {
    tallest = 0;
    
    $(group).each(function() {
        thisHeight = $(this).height();
        if(thisHeight > tallest) {
            tallest = thisHeight;
        }
    });
    $(group).each(function() {
    	$(this).height(tallest);	
	});
}

$(document).ready(preparePage);