var remove = new Array();
var optionsWindow;
var banners = new Array();

function addLoadEvent(func) {
	//alert('load event');
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}


function addUnLoadEvent(func) {
    //alert('Unload event');
  var oldunload = window.unload;
  if (typeof window.unload != 'function') {
    window.unload = func;
  } else {
    window.unload = function() {
      if (oldunload) {
        oldunload();
      }
      func();
    }
  }
}

/***********************************************************
* 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.innerHTML = 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);
	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", 'Please enter a valid email 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
		msg (infoID, "valid", "", 3);
  		return true;
	}

	var numberRE = new RegExp(/^[0-9 ]*$/);
	if (!numberRE.test(tfld)) {
		msg (infoID, "warning", 'Please enter 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 exclude = new Array();
	
	id = $(form).attr('id');

	var infoLinks = $('#'+id+' span.required');
	infoLinks.each(function(i) {
		//alert(infoLinks[i].id);
		$(this).innerHTML = '';
	});

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

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

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

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

	var agreeLinks = $('#'+id+' input.agreed');
	agreeLinks.each(function(i) {
		//alert('info_'+agreeLinks[i].name);
		el = document.getElementById($(this).attr('id'));
		if (!validateagreed(el, 'info_'+$(this).attr('id'))) errs +=1;
	});
		
	var checkboxRanges = $('#'+id+' input:hidden.checkboxRange');
	checkboxRanges.each(function(i) {
		var numChecked = 0;
		$('input:checkbox.'+this.id).each(function(x){
			if(this.checked == true) {
				numChecked++;
			}
		});
		
		var min = 0;
		if($('#'+this.id+'_min').length>0) {
			min = $('#'+this.id+'_min')[0].value;
		}
		
		if(this.value<numChecked) {
			msg ('info_'+this.id, "warning", this.title, 1);
			errs++;
		}
		else if(min>numChecked) {
			msg ('info_'+this.id, "warning", $('#'+this.id+'_min')[0].title, 1);
			errs++;
		}
		else {
			msg ('info_'+this.id, "valid", "", 1);
		}
	});

	return (errs==0);
};

/***********************************************************
* Set up the links in the page with their onblur and onsubmit handlers
************************************************************/
function preparePage(){
	if(document.getElementById('address_form_del_same_as_bill')){
		var del_same_as_bill = document.getElementById('address_form_del_same_as_bill');
		del_same_as_bill.onclick = function(){
		    if(del_same_as_bill.checked==true){
				document.getElementById('address_form_del_address1').className = '';
				document.getElementById('address_form_del_address1').value = document.getElementById('address_form_address1').value;
				document.getElementById('address_form_del_address2').value = document.getElementById('address_form_address2').value;
				document.getElementById('address_form_del_address3').value = document.getElementById('address_form_address3').value; 
				document.getElementById('info_address_form_del_address1').className = '';
				document.getElementById('info_address_form_del_address1').firstChild.nodeValue = '';

				document.getElementById('address_form_del_town').className = 'town';
				document.getElementById('address_form_del_town').value = document.getElementById('address_form_town').value;
				document.getElementById('info_address_form_del_town').className = '';
				document.getElementById('info_address_form_del_town').firstChild.nodeValue = '';

				document.getElementById('address_form_del_county').className = 'town';
				document.getElementById('address_form_del_county').value = document.getElementById('address_form_county').value;
				document.getElementById('info_address_form_del_county').className = '';
				document.getElementById('info_address_form_del_county').firstChild.nodeValue = '';

				document.getElementById('address_form_del_postcode').className = 'postcode';
				document.getElementById('address_form_del_postcode').value = document.getElementById('address_form_postcode').value;
				document.getElementById('info_address_form_del_postcode').className = '';
				document.getElementById('info_address_form_del_postcode').firstChild.nodeValue = '';

				document.getElementById('address_form_del_country').className = '';
				document.getElementById('address_form_del_country').value = document.getElementById('address_form_country').value;
				document.getElementById('info_address_form_del_country').className = '';
				document.getElementById('info_address_form_del_country').firstChild.nodeValue = '';
		    } else {
				document.getElementById('address_form_del_address1').className = 'require';
				document.getElementById('info_address_form_del_address1').className = 'required';
				document.getElementById('info_address_form_del_address1').firstChild.nodeValue = '';

				document.getElementById('address_form_del_town').className = 'town require';
				document.getElementById('info_address_form_del_town').className = 'required';
				document.getElementById('info_address_form_del_town').firstChild.nodeValue = '';

				document.getElementById('address_form_del_county').className = 'town require';
				document.getElementById('info_address_form_del_county').className = 'required';
				document.getElementById('info_address_form_del_county').firstChild.nodeValue = '';

				document.getElementById('address_form_del_postcode').className = 'postcode require';
				document.getElementById('info_address_form_del_postcode').className = 'required';
				document.getElementById('info_address_form_del_postcode').firstChild.nodeValue = '';

				document.getElementById('address_form_del_country').className = 'require';
				document.getElementById('info_address_form_del_country').className = 'required';
				document.getElementById('info_address_form_del_country').firstChild.nodeValue = '';
		    }
	    }
    }

	if(document.getElementById('form_1_agree_terms')){
		var agree_terms = document.getElementById('form_1_agree_terms');
		agree_terms.onclick = function(){
			if(agree_terms.checked==true){
				document.getElementById('info_form_1_agree_terms').className = '';
				document.getElementById('info_form_1_agree_terms').firstChild.nodeValue = '';
			} else {
				document.getElementById('info_form_1_agree_terms').className = 'agree';
				document.getElementById('info_form_1_agree_terms').firstChild.nodeValue = '*';
			}
		}
	}
	
	//Open all links rel="nofollow" in a new window
	$("a[rel*='nofollow']").click(function() { window.open($(this).attr('href')); return false; });
	
	//Open all links rel="external" in a new window
	$("a[rel*='external']").click(function() { window.open($(this).attr('href')); return false; });
	
	//var forms = getElementsByClassName('validate','form');
	var forms = $('form.validate');
	//for (var i=0; i < forms.length; i++){
	forms.each(function(i) {
		$(this).bind('submit',function(){	
			return validateOnSubmit(this);
		});
	});

	//var pop_ups = getElementsByClassName('pop','a');
	var pop_ups = $('a.pop');
	//for (var i=0; i < pop_ups.length; i++){
	pop_ups.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;
		});
	});
	
	async_submit();
	expose_state();
	
	var input_count = 0;
	var segments = $("input[name*='segment[']");
	
	segments.each(function(el){
		if($(this).val()!=$(this).attr('rel')){
			//$("#product_purchase").clearForm(new Array('pid'));
			$(this).val('');
		}
		
		var input = $(this);
		
		var label = $("label[for='" + $(this).attr('id') + "']");
		var list_item = label.parent();
		//new_image.appendTo(list_item);
		var remove_links = list_item.children('a.remove');
		remove_links.unbind('click');
		remove_links.bind('click',function(){
//			alert('Remove Link');
			input.val('');
			input.removeAttr('val');
			input.siblings('img').remove();
			label.text('Please choose a fabric from the list below');
			$('#segment_message').hide();
			$(this).css('display','none');
			$('#submit_order').attr('src', '/images/disabled_order.gif');	
			$('#product_purchase').bind('submit',function(){	
				$('#segment_message').show();
				msg('segment_message', 'error', 'Please choose the stool\'s fabric from the list below', 1);
				return false;
			});
			return false;
		});
		
		if($(this).val()==''){
			return false;	
		}
		input_count++;
	});
	
//	alert(input_count);
	
	if(input_count == segments.size()){
		$('#submit_order').attr('src', '/images/order.gif');
		$('#product_purchase').unbind('submit');
	} else {
		$('#submit_order').attr('src', '/images/disabled_order.gif');	
		$('#product_purchase').bind('submit',function(){	
			$('#segment_message').show();
			msg('segment_message', 'error', 'Please choose the stool\'s fabric from the list below', 1);
			return false;
		});
	}
	
	
}

function async_submit(){
	var links = $('a.async');
	var ajax_loader = new Image();
	ajax_loader.src = '/images/ajax-loader.gif';
	links.each(function(i) {
	    $(this).bind('click',function(){   
	    	var id = $(this).parent().parent().attr('id');  
	    	var link = this;

	    	if($("#list_"+id).is(':visible')){
				$("#list_"+id+" ul").slideUp('normal', function(){
					$("#list_"+id).hide();
				});
				$("#list_"+id).fadeOut();
				$(link).removeClass('up');
            	$(link).addClass('down');
			} else {
				$(link).removeClass('down');
                $(link).addClass('up');
                			
				if($("#list_"+id).is(':hidden')){
					$("#list_"+id+" ul").fadeIn();
					$("#list_"+id).slideDown();
				} else {
					$(link).removeClass('down');
					$(link).removeClass('up');
                	$(link).addClass('loading');
					$.ajax({
						type: "GET",
						url: $(this).attr('href'),
						data: "async=true",
						success: function(html){
							$("#"+id).append(html);
							$("#list_"+id).hide();
							setTimeout(function(){
								$("#list_"+id+" ul").fadeIn();
								$("#list_"+id).slideDown();
								//$(link).css('background', '');
								$(link).removeClass('down');
								$(link).removeClass('loading');
                				$(link).addClass('up');
							}, 1000);
							
							jQuery(function($) {
								$("a[rel^='lightbox']").slimbox({/* Put custom options here */}, null, function(el) {
									return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
								});
							});
							
							expose_state();
						}
					});
				}
			}
	         return false;
	    });
	});		
}

function expose_state(){
	$('a.select_fabric').unbind('click');
	$('a.select_fabric').bind('click',function(){
		var colour_ID = $(this).attr('rel');
		var allOwnFabric = false;
		if(colour_ID == 'own_all') {
			allOwnFabric = true;
			colour_ID = 'own';
		}
		var link = $(this);
		
		var targetOffset = $('#state').offset().top;
		targetOffset = targetOffset-100;
		$('html,body').animate({scrollTop: (targetOffset)}, 1000);
		
		$('#segment_message').hide();
		
		var segment_remaining = false;
		var input_count = 0;
		var segments = $("input[name*='segment[']");
		
		segments.each(function(el){
			if($(this).val()==''){
				var input = $(this);
				input.val(colour_ID);
				var label = $("label[for='" + $(this).attr('id') + "']");
				var list_item = label.parent();
				label.text((link.siblings('span.title')).text());
				var new_image = $('#fabric_image_'+colour_ID).clone();
				new_image.removeAttr('id');
				//new_image.appendTo(list_item);
				var remove_links = list_item.children('a.remove');
				remove_links.unbind('click');
				remove_links.bind('click',function(){
					input.val('');
					input.removeAttr('val');
					input.siblings('img').remove();
					label.text('Please choose a fabric from the list below');
					$('#segment_message').hide();
					$(this).css('display','none');
					$('#submit_order').attr('src', '/images/disabled_order.gif');	
					$('#product_purchase').bind('submit',function(){	
						$('#segment_message').show();
						msg('segment_message', 'error', 'Please choose the stool\'s fabric from the list below', 1);
						return false;
					});
					return false;
				}).show();
				new_image.insertBefore(label);
				segment_remaining = true;
				if(allOwnFabric==false)
					return false;
			}
		});
		
		segments.each(function(el){						
			if($(this).val()==''){
				return false;	
			}
			input_count++;
		});
		
		if(input_count == segments.size()){
			$('#submit_order').attr('src', '/images/order.gif');
			$('#product_purchase').unbind('submit');
		} else {
			$('#submit_order').attr('src', '/images/disabled_order.gif');	
			$('#product_purchase').bind('submit',function(){	
				$('#segment_message').show();
				msg('segment_message', 'error', 'Please choose the stool\'s fabric from the list below', 1);
				return false;
			});
		}
		
		if(segment_remaining==false){
			$('<div id="segment_message">You have selected a colour for all of the segments available for your stool, please place your order or remove a fabric to continue.</div>').insertAfter('#product_purchase h2');
			$('#segment_message').addClass('error');
		}
		
	    return false;	
	});
	
	
}

$.fn.clearForm = function(exclude) {
	return this.each(function() {
		var type = this.type, tag = this.tagName.toLowerCase();

		for(var i=0; i<exclude.length; i++) {
			if(this.id==exclude[i]){
				return false;
			}
		}

		if (tag == 'form')
			return $(':input',this).clearForm(exclude);
		if (type == 'text' || type == 'password' || tag == 'textarea' || type == 'hidden')
			this.value = '';
		else if (type == 'checkbox' || type == 'radio')
			this.checked = false;
		else if (tag == 'select')
			this.selectedIndex = -1;
	});
};

addLoadEvent(preparePage);
