$(document).ready(function() {
	var slidesAdded = false;

	$('#messagebar').hide();
	setTimeout('$(".messagerow").slideUp()',5000);
	
	// $('#parent').dropShadow({left: 2, top: 2, opacity: 1.0, blur: 4});
	$('#q').focus(function(){ if($(this).val()=='search')$(this).val(''); });
	$('#q').blur(function(){ if($(this).val()=='')$(this).val('search'); });
	$('#bttq').click(function(){ if($('#q').val()=='search'||$('#q').val()==''){$('#q').focus();return false;} });
	
	// status messages
	$('#statusmessagebar').click(function(){ $(this).fadeOut(); });
	
	// homepage gallery
	$('#gallerypreviewholder').cycle();
	
	// employees block
	$('#employees li#displaypane div.imagepanel').cycle();
	$('#employees li#displaypane').hide();
	$('#employees li ul#employeeslist a.showbio').click(function(){ 
		eid=$(this).attr('href');
		lang=$(this).attr('lang');
		// alert(lang);
		$('#employees li#displaypane').slideDown();
		$('#employees li#displaypane').html('Loading...');
		datastr='task=loademployeepanel'
		datastr=datastr+'&id='+eid+'&lang='+lang;
		$.ajax({
			type: "POST",
			url: basepath+'ajax.php',
			data: datastr,
			success: function(html){
				$('#employees li#displaypane').html(html);
				$('#employees li#displaypane div.imagepanel').cycle({fx:'shuffle'});
			}
		});	
		return false;
	});
	$('#employees li ul#employeeslist a.showbio').live('click',function(){ 
		eid=$(this).attr('href');
		lang=$(this).attr('lang');
		// alert(lang);
		$('#employees li#displaypane').slideDown();
		$('#employees li#displaypane').html('Loading...');
		datastr='task=loademployeepanel'
		datastr=datastr+'&id='+eid+'&lang='+lang;
		$.ajax({
			type: "POST",
			url: basepath+'ajax.php',
			data: datastr,
			success: function(html){
				$('#employees li#displaypane').html(html);
				$('#employees li#displaypane div.imagepanel').cycle({fx:'shuffle'});
			}
		});	
		return false;
	});
	$('a#closedisplaypane').live('click',function(){ $('#employees li#displaypane').slideUp(); return false; });
	$('#employees #tabs a').click(function(){ 
		$('#employees #tabs a').removeClass('selected');
		$(this).addClass('selected');
		dept=$(this).attr('href');
		lang=$(this).attr('lang');
		// alert(lang);
		datastr='task=loadEmployees'
		datastr=datastr+'&dept='+dept+'&lang='+lang;
		$.ajax({
			type: "POST",
			url: basepath+'ajax.php',
			data: datastr,
			success: function(html){
				$('#employees li ul#employeeslist').html(html);
			}
		});	
		return false;
	});
	
	$('#frmRequestCatalogue').hide();
	$('#requestCatalogueLink').click(function(){ $('#frmRequestCatalogue').slideToggle(); return false; });
	$('#bttCloseRequest').click(function(){ $('#frmRequestCatalogue').slideUp(); return false; });
	
	// admin login
	$('#bttSubmitCatalogueRequest').click(function(){
		
		datastr='task=sendcataloguerequest'
		datastr=datastr+'&name='+$('#txtName').val();
		datastr=datastr+'&company='+$('#txtCompany').val();
		datastr=datastr+'&activity='+$('#txtActivity').val();
		datastr=datastr+'&jobtitle='+$('#txtJobTitle').val();
		datastr=datastr+'&email='+$('#txtEmail').val();
		datastr=datastr+'&phone='+$('#txtPhone').val();
		datastr=datastr+'&address='+$('#txtAddress').val();
		
		$('#frmRequestCatalogue').html('Sending... please wait...');
		
		$.ajax({
			type: "POST",
			url: basepath+'ajax.php',
			data: datastr,
			success: function(html){
				if(html=='valid'){
					$('#frmRequestCatalogue').html('Your request has been sent.');
				}
				else{
					$('#frmRequestCatalogue').html('Sorry. An error has occurred and your request has not been sent.<br /><br />Please try again later');
					return false;
				}
			}
		});	
	});
	
	// registration and login
	$('#usermgmtlist li.formholder').hide();
	$('#usermgmtlist li a').click(function(){
		$('#usermgmtlist li.formholder:visible').slideUp();
		$('#usermgmtlist li a').removeClass('selected');
		$(this).addClass('selected');
		elmid=$(this).attr('href');
		$(elmid).slideDown();
		return false;
	});
	$('#bttLogin').click(function(){
		err=0;
		tofill=''
		if($('#frmLogin #txtUName').attr('value')==''){ err++;tofill=tofill+'\n- email'; }
		if($('#frmLogin #txtPswd').attr('value')==''){ err++;tofill=tofill+'\n- password'; }
		
		if(err>0){
			alert('Please complete the obligatory fields: '+tofill);
			return false;
		}
		else{
			$('#frmLogin').submit();
		}
	});
	$('#bttRegister').click(function(){
		err=0;
		tofill=''
		if($('#frmRegister #txtFName').attr('value')==''){ err++;tofill=tofill+'\n- first name'; }
		if($('#frmRegister #txtLName').attr('value')==''){ err++;tofill=tofill+'\n- last name'; }
		if($('#frmRegister #txtEmail').attr('value')==''){ err++;tofill=tofill+'\n- email'; }
		if($('#frmRegister #txtCompany').attr('value')==''){ err++;tofill=tofill+'\n- company'; }
		if($('#frmRegister #txtPhone').attr('value')==''){ err++;tofill=tofill+'\n- phone'; }
		
		if(err>0){
			alert('Please complete the obligatory fields: '+tofill);
			return false;
		}
		else{
			$('#frmRegister').submit();
		}
	});
	
	// add to cart
	$('#cart_user_fields').hide();
	$('#cart_register_fields').hide();
	/*$('#bttAddToCart').click(function(){
		status=$('#formtype').attr('value');
		alert(status);
		if(status=='requirelogin'){
			window.location='register.php';
		}
		return false;
	});
	$('#link-register').click(function(){
		$('#cart_register_fields').slideDown();
		$('#formtype').attr('value','requireregistration');
		return false;
	});*/
	$('#bttAddToCartLoggedIn').click(function(){
		currentitems=parseFloat($('#cartcount').html());
		productid=$('#productid').attr('value');
		material=$('#selMaterial').attr('value');
		colour=$('#selColour').attr('value');
		qty=$('#selQuantity').attr('value');
		
		datastr='task=addToCart'
		datastr=datastr+'&productid='+productid;
		datastr=datastr+'&materialid='+material;
		datastr=datastr+'&colourid='+colour;
		datastr=datastr+'&qty='+qty;
		
		$('#frmAddToCart ul').html('<li>Adding to cart...</li>');
		
		$.ajax({
			type: "POST",
			url: basepath+'ajax.php',
			data: datastr,
			success: function(html){
				$('#frmAddToCart ul').html(html);
				$('#cartcount').html(currentitems+1);
				if(currentitems<=1)$('li.actionbar').fadeOut();
				// $('#frmAddToCart ul').html('<li>Added to cart.</li>');
			}
		});	
		
		return false;
	});
	
	// cart listing
	$('ul.cartblock li span.details').hide();
	$('a.showdetails').click(function(){
		elmid=$(this).attr('href');
		$(elmid).slideToggle();
		return false;
	});
	$('a.removeorder').click(function(){
		if(!confirm('Remove order: Are you sure?'))return false;
		orderid=$(this).attr('href');
		orderrowid='li#'+orderid;
		datastr='task=removeOrder';
		datastr=datastr+'&orderid='+orderid;
		$.ajax({
			type: "POST",
			url: basepath+'ajax.php',
			data: datastr,
			success: function(html){
				$(orderrowid).fadeOut();
				currentitems=parseFloat($('#cartcount').html());
				$('#cartcount').html(currentitems-1);
				if(currentitems<=1)$('li.actionbar').fadeOut();
			}
		});	
		return false;
	});
	$('a.clearCart').click(function(){
		if(!confirm('Remove all cart items: Are you sure?'))return false;
		datastr='task=clearCart';
		$.ajax({
			type: "POST",
			url: basepath+'ajax.php',
			data: datastr,
			success: function(html){
				$('li.order').fadeOut();
				$('#cartcount').html('0');
				$('li.actionbar').fadeOut();
			}
		});	
		return false;
	});
	$('a.sendOrder').click(function(){
		if(!confirm('Send order and clear cart: Are you sure?'))return false;
		$(this).html('Sending... please wait...');
		datastr='task=sendOrder';
		$.ajax({
			type: "POST",
			url: basepath+'ajax.php',
			data: datastr,
			success: function(html){
				$('li.order').fadeOut();
				$('#cartcount').html('0');
				$('li.actionbar').html(html);
			}
		});	
		return false;
	});
	
});


//GENERIC FUNCTIONS
function addslashes (str) {
    return (str+'').replace(/([\\"'+])/g, "\\$1").replace(/\u0000/g, "\\0");
}
function selectOptionByValue(elmid,val){
	elm=document.getElementById(elmid);
	elmoptions=elm.options;
	elmlen=elmoptions.length;
	for(i=0;i<elmlen;i++){
		if(elm.options[i].value==val){
			elm.options[i].selected=true;
		}
	}
}
function toggleTableRow(elmid){
	elm=document.getElementById(elmid);
	if(elm.style.visibility=='hidden'){
		elm.style.display='';
		elm.style.visibility='visible';
	}
	else{
		elm.style.display='none';
		elm.style.visibility='hidden';
	}
}

//FORM VALIDATION
function highlightOn(elm){
	f=document.getElementById(elm);
	f.style.backgroundColor="#FBE5EA";
	f.style.color="#333333";
}
function highlightOff(elm){
	f=document.getElementById(elm);
	f.style.backgroundColor="#FFFFFF";
	f.style.color="#333333";
}
function checkPassword(f1,f2){
	pswd1=document.getElementById(f1).value;
	pswd2=document.getElementById(f2).value;
			
	if(pswd1.length>0&&pswd1==pswd2){
		highlightOff(f1);
		highlightOff(f2);
		return true;
	}
	else{
		highlightOn(f1);
		highlightOn(f2);
		return false;
	}
}
function checkForm(){
	err=0;
	
	fieldstocheck=new Array();
	fieldstocheck=['f2','f3','f12','f15','f18','f22','f24'];
	for(var i=0;i<fieldstocheck.length;i++){
		fieldid=fieldstocheck[i];
		field=document.getElementById(fieldid);
		if(field.value.length==0){err++;highlightOn(fieldid);}else{highlightOff(fieldid);}
	}
	
	//check for password confirmation
	if(!checkPassword())err++;
	
	// test email against a regular expression
	var emailrule = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$");
	if(!emailrule.test(email.value)){
		err++;
		highlightOn('f5');	
	}
	else{
		highlightOff('f5');	
	}
	
	if(err==0){
		document.getElementById("registrationform").submit();
	}
	else{
		alert("Please complete the hightlighted fields with valid entries");
	}
}

//TEXTAREA RESIZING
// Place [onload="cleanForm();"] on body tag
function countLines(strtocount, cols) {
    var hard_lines = 1;
    var last = 0;
    while ( true ) {
        last = strtocount.indexOf("\n", last+1);
        hard_lines ++;
        if ( last == -1 ) break;
    }
    var soft_lines = Math.round(strtocount.length / (cols-1));
    var hard = eval("hard_lines  " + unescape("%3e") + "soft_lines;");
    if ( hard ) soft_lines = hard_lines;
    return soft_lines;
}
function cleanForm() {
	for(i=0;i<document.forms.length;i++){
	    var the_form = document.forms[i];
	    for ( var x in the_form ) {
	        if ( ! the_form[x] ) continue;
	        if( typeof the_form[x].rows != "number" ) continue;
	        the_form[x].rows = countLines(the_form[x].value,the_form[x].cols) +1;
	    }
	}
    setTimeout("cleanForm();", 300);
}
