var FE;
$(document).ready(function(){
	//IE Drop downs
	if (window.attachEvent) window.attachEvent("onload", sfHover);
	//External Links
	externalLinks();
	//Scripts Class
	FE = new CFE();
	//cycle
	 $('.sideimage').cycle({
		fx: 'fade',
		timeout: 10000,
		speed: 3000
	});
	$('#LoginEmail').keypress(function(e) {
	    if(e.keyCode == 13) {
    	    FE.Submit('frmLogin')
	    }									   	
	});
	$('#LoginPassword').keypress(function(e) {
	    if(e.keyCode == 13) {
    	    FE.Submit('frmLogin')
	    }									   	
	});
});

function externalLinks() { 
	if (!document.getElementsByTagName) return; 
	var anchors = document.getElementsByTagName("a"); 
	for (var i=0; i<anchors.length; i++) { 
		var anchor = anchors[i]; 
		if (anchor.getAttribute("href") && 
			(anchor.getAttribute("rel") == "external" || anchor.getAttribute("rel") == "external nofollow") )
			anchor.target = "_blank"; 
	} 
}
sfHover = function() {
	var sfEls = document.getElementById("menu").getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
}

function CFE() {
	var main = this;
	this.AddToBasket = function(){
		$.ajax({
			type : 'post',
			url : '/account/Actions.asp?act=1',
			data : formData2QueryString(document.forms['frmAddBasket']),
			success : function(html) {
				//alert(html)
				main.UpdateBasketTotal();
				main.UpdateBasketItems();
				alert('Item added to shopping bag');
			},
			error : function(XMLHttpRequest, textStatus, errorThrown) {
				alert(textStatus+'\n\n'+XMLHttpRequest.responseText);
				//what should we do in the event of an error
				alert('An error has occured.  Please try logging in and trying the operation again.');
			}
		})
	};
	this.AddToBasket2 = function(ProductID){
		$.ajax({
			type : 'get',
			url : '/account/Actions.asp?act=1&ProductID='+ProductID+'&Quantity=1',
			success : function(html) {
				main.UpdateBasketTotal();
				main.UpdateBasketItems();
				alert('Item added to shopping bag');
			},
			error : function(XMLHttpRequest, textStatus, errorThrown) {
				//alert(textStatus+'\n\n'+XMLHttpRequest.responseText);
				alert('An error has occured.  Please try logging in and trying the operation again.');
			}
		})
	};
	/*this.MinimumQuantity = function(minimum,id){
		var value = $('#'+id).val();
		if(value<minimum){
			$('#'+id).val(minimum);
			alert('The minimum order quantity is '+minimum+' for this product.');
		}
	}*/
	this.UpdateBasketQuantity = function(BC,Q) {
		$.ajax({
			type : 'get',
			url : '/account/Actions.asp?act=2&BC='+BC+'&Q='+Q,
			success : function(html) {
				window.location='/account/basket.asp';
			},
			error : function(XMLHttpRequest, textStatus, errorThrown) {
				alert(textStatus+'\n\n'+XMLHttpRequest.responseText);
				//what should we do in the event of an error
				//alert('An error has occured.  Please try logging in and trying the operation again.');
			}
		});
	};
	this.RemoveFromBasket = function(BC) {
		$.ajax({
			type : 'get',
			url : '/account/Actions.asp?act=3&BC='+BC,
			success : function(html) {
				window.location='/account/basket.asp';
			},
			error : function(XMLHttpRequest, textStatus, errorThrown) {
				alert(textStatus+'\n\n'+XMLHttpRequest.responseText);
				//what should we do in the event of an error
				//alert('An error has occured.  Please try logging in and trying the operation again.');
			}
		});
	};
	this.Confirm = function(Message) {
		if(confirm(Message)) {
			return true;
		} else {
			return false;
		}
	};
	this.UpdateBasketTotal = function() {
		$.ajax({
			type : 'get',
			url : '/account/Actions.asp?act=5',
			success : function(html) {
				$('#BasketTotal').html(html);
			},
			error : function(XMLHttpRequest, textStatus, errorThrown) {
				alert(textStatus+'\n\n'+XMLHttpRequest.responseText);
				//what should we do in the event of an error
				//alert('An error has occured.  Please try logging in and trying the operation again.');
			}
		});
	};
	
	this.UpdateBasketItems = function() {
		$.ajax({
			type : 'get',
			url : '/account/Actions.asp?act=7',
			success : function(html) {
				$('#BasketItems').html(html);
			},
			error : function(XMLHttpRequest, textStatus, errorThrown) {
				alert(textStatus+'\n\n'+XMLHttpRequest.responseText);
				//what should we do in the event of an error
				//alert('An error has occured.  Please try logging in and trying the operation again.');
			}
		});
	};
	
	this.LoadAddress = function(a,id) {
		$.ajax({
			type : 'get',
			url : '/account/Actions.asp?act=6&a='+a+'&i='+id,
			success : function(html) {
				$('#'+id).html(html);
			},
			error : function(XMLHttpRequest, textStatus, errorThrown) {
				alert(textStatus+'\n\n'+XMLHttpRequest.responseText);
				//what should we do in the event of an error
				//alert('An error has occured.  Please try logging in and trying the operation again.');
			}
		});
	};
	this.CopyAddress = function(FromID, ToID) {
		var fieldArray = Array('Title','Firstname','Surname','Address1','Address2','Address3','Town','County','Country','Postcode','Phone','CountryID');
		for (var field in fieldArray) {
			$('#'+ToID+fieldArray[field]).val($('#'+FromID+fieldArray[field]).val());
		}
	};
	this.Submit = function(frmName) {
		document.forms[frmName].submit();
	};
	this.UpdateAS = function() {
		var output = '';
		var updateArray = $('#ALUpdateList').val().split(',');
		for (var i in updateArray) {
			if(updateArray[i].toString() != '') {
				output += $('#'+updateArray[i]+' option:selected').text()+', '
			}
		}
		output = output.slice(0, -2)
		$('#ProdIdentifier').html(output);
	};
	this.LoadPrices = function(c,s) {
		$('.'+c).each(function() {
			$('#'+this.id).html('Loading...')
		});
		$('.'+c).each(function() {
			main.LoadPrice(this.id,$('#'+this.id).data('pd'),s);
		});
	};
	this.LoadPrice = function(id,p,s){
		$.ajax({
			type : 'get',
			url : '/account/Actions.asp?act=10&p='+p+'&s='+s,
			success : function(html){
				//alert(html);
				if(html=='-:-'){
					$('#'+id).html('Not available in this region');
					$('#chk'+id).attr('checked',false);
					$('#chk'+id).attr('disabled','disabled');
				}else{
					a=html.split(':')
					$('#'+id).html('&pound;'+a[0]);
					$('#chk'+id).val(a[1]);
					$('#chk'+id).removeAttr('disabled');
				}
			},
			error : function(XMLHttpRequest,textStatus,errorThrown){
				alert(textStatus+'\n\n'+XMLHttpRequest.responseText);
				//alert('An error has occured.  Please try logging in and trying the operation again.');
			}
		});
	};
	this.Enrol = function(){
		//alert(formData2QueryString(document.forms['frmAddBasket']));
		var Region = $('#ATT3').val();
		var Course = $('#frmAddBasket .Course:checked').val();
		if(Course==undefined || Region==0){
			alert('You must select a region and at least one course to enrol!');
		}else{
			$.ajax({
				type : 'post',
				url : '/account/Actions.asp?act=11',
				data : formData2QueryString(document.forms['frmAddBasket']),
				success : function(html){
					window.location='/account/basket.asp';
				},
				error : function(XMLHttpRequest,textStatus,errorThrown){
					alert(textStatus+'\n\n'+XMLHttpRequest.responseText);
				}
			});
		}
	};
	this.toggleSections = function(classHide, showID, thisClass, thisID) {
		$('.'+classHide).slideUp('fast');
		$('#'+showID).slideDown('fast');
		$('.'+thisClass).removeClass('current');
		$('#'+thisID).addClass('current');
	};
	this.AddPromo = function(b,p,d) {
		$.ajax({
			type : 'get',
			url : '/account/Actions.asp?act=8&b='+b+'&p='+p+'&d='+d,
			success : function(html) {
				$('#Basket').html(html);
			},
			error : function(XMLHttpRequest, textStatus, errorThrown) {
				//alert('An error has occured.  Please try logging in and trying the operation again.');
				alert(textStatus+'\n\n'+XMLHttpRequest.responseText);
			}
		});
	};
	this.OrderBy = function(OB){
		$('#order-field').val(OB);
		main.Submit('order-by-form');
	};
	this.ShowTab = function(id){
		$('.productTab').hide();
		$('#productTabs a').removeClass('active');
		$('#product'+id).show();
		$('#productTabs #tab'+id).addClass('active');
	};
	this.ViewType = function(vt) {
		$.ajax({
			type : 'get',
			url : '/account/Actions.asp?act=9&vt='+vt,
			success : function(html) {
			},
			error : function(XMLHttpRequest, textStatus, errorThrown) {
				//alert(textStatus+'\n\n'+XMLHttpRequest.responseText);
				//what should we do in the event of an error
				//alert('An error has occured.  Please try logging in and trying the operation again.');
			}
		});
		//change current view
		if(vt==2) {
			$('ul.category').addClass('list');
			$('#ViewType2').addClass('active');
			$('#ViewType1').removeClass('active');
		} else {
			$('ul.category').removeClass('list');
			$('#ViewType1').addClass('active');
			$('#ViewType2').removeClass('active');
		}
	};
}

function shorten(s, outputLength) {
	return s.substr(s.length-outputLength);
}

function formData2QueryString(docForm) {

	var strSubmitContent = '';
	var formElem;
	var strLastElemName = '';
	
	for (i = 0; i < docForm.elements.length; i++) {
		
		formElem = docForm.elements[i];
		switch (formElem.type) {
			// Text fields, hidden form elements
			case 'text':
			case 'hidden':
			case 'password':
			case 'textarea':
			case 'select-one':
				strSubmitContent += formElem.name + '=' + escape(formElem.value).replace(/\+/g,'%2B') + '&'
				break;
				
			// Radio buttons
			case 'radio':
				if (formElem.checked) {
					strSubmitContent += formElem.name + '=' + escape(formElem.value) + '&'
				}
				break;
				
			// Checkboxes
			case 'checkbox':
				if (formElem.checked) {
					// Continuing multiple, same-name checkboxes
					if (formElem.name == strLastElemName) {
						// Strip of end ampersand if there is one
						if (strSubmitContent.lastIndexOf('&') == strSubmitContent.length-1) {
							strSubmitContent = strSubmitContent.substr(0, strSubmitContent.length - 1);
						}
						// Append value as comma-delimited string
						strSubmitContent += ',' + escape(formElem.value);
					}
					else {
						strSubmitContent += formElem.name + '=' + escape(formElem.value);
					}
					strSubmitContent += '&';
					strLastElemName = formElem.name;
				}
				break;
				
		}
	}
	
	// Remove trailing separator
	strSubmitContent = strSubmitContent.substr(0, strSubmitContent.length - 1);
	return strSubmitContent;
}
