var Cesc = {
	Calendar : {
		NextMonth:function(year,month) {
			var url = "index.cfm?action=Calendar_NextMonth&year="+year+"&month="+month;
			new Ajax.Request( url, {asynchronous:true, evalScripts:false, onSuccess:Cesc.Calendar.NextMonth_onSuccess, onFailure:errFunc});
			return false;
		},
		NextMonth_onSuccess:function(t) {
			z = parseJSON(t.responseText);
			$("calendarPlaceholder").update(z.calendarHTML);
		},
		PreviousMonth:function(year,month) {
			var url = "index.cfm?action=Calendar_PreviousMonth&year="+year+"&month="+month;
			new Ajax.Request( url, {asynchronous:true, evalScripts:false, onSuccess:Cesc.Calendar.PreviousMonth_onSuccess, onFailure:errFunc});
			return false;
		},
		PreviousMonth_onSuccess:function(t) {
			z = parseJSON(t.responseText);
			$("calendarPlaceholder").update(z.calendarHTML);
		}
	},	
	ChangeProductView:function(id) {
		var ppId = $("productChanger").value;
		if(ppId!=0) {			
			var url = "index.cfm?action=Products_GetProductDetails&id="+id+"&ppId="+ppId;
			new Ajax.Request( url, {asynchronous:true, evalScripts:false, onSuccess:Enibas.ChangeProductView_onSuccess, onFailure:errFunc});
		}
	}	
	,ChangeProductView_onSuccess:function(t) {
		z = parseJSON( t.responseText );
		$("productImage").src = "contentFiles/products/" + z.fullImage;
		$("productPriceEuro").innerHTML = z.price;
		$("productPriceUSD").innerHTML = "(appr. $"+z.usdprice+" , &pound;" + z.gbpprice + ")";
		$("ppId").value = z.ppId;
		$("productDetailGrid").update(z.productHTML);
	}	
}

function LoadingAjax(txt) {
	if(typeof(txt)=="undefined") {
		txt = "Loading...";
	}
	return "<div class='ajaxMsg' id='widgetAjaxMsg'> "+txt+"</div>";
}

function parseJSON( json ){
	var o = eval('(' + json + ')');
	if( o.redirectURL )
	{
		document.location = o.redirectURL;
		return;
	}
	if( $("message") != null ) new Element.remove( "message" );
	if( o.errMsg )
	{
		if( o.errMsgTitle == null ) o.errMsgTitle = "Error";
		if( o.errMsgTimer == null ) o.errMsgTimer = 5000;
		tw.ShowMessage( o.errMsgTitle, o.errMsg, "error", o.errMsgTimer, o.errMsgPosition );
		return o;
	}
	if( o.msgTitle || o.msg )
	{
		if( o.msgTimer == null ) o.msgTimer = 5000;
		tw.ShowMessage( o.msgTitle, o.msg, o.msgClass, o.msgTimer, o.msgPosition );
	}
	return o;
}

var errFunc = function(t) {
	var win = window.open("", "win", "width=1024,height=700,resizable=yes,scrollbars=yes,status=no"); // a window object
	win.document.open("text/html", "replace");
	win.document.write( "<html><body style='margin:0'><div style='border-bottom:1px solid #222;background:#666;padding:10px;'><h1 style='color:#FFF;margin:0;padding:0;'>Digital Crew Ajax Error</h1></div><div style='padding:10px;'>"+t.responseText.replace(/^\s+|\s+$/, '') + "</div></body></html>" );
	win.document.close();
	win.focus();
}

var ShoppingCart = {
	ShowCVVInfo:function(){
		$("cvvMore").style.display = "none";
		$("cvvInfo").style.display = "block";
	}
	,ChangeCC:function(obj) {
		var cc = obj.value;
		$("ccImage").src="images/creditcards/" + cc + ".png";
		switch(cc) {
			case "laser":
				$("CVVNumberHolder").hide();
			break;
			case "visa":
				$("CVVNumberHolder").show();
			break;
			case "mastercard":
				$("CVVNumberHolder").show();
			break;
			case "amex":
				$("CVVNumberHolder").show();
			break;
		}
		$("ccError").update("&nbsp;");
		$("ccNumber").focus();
	},
	HighlightAndFocus:function(id) {		
		new Effect.Highlight($(id),{startcolor:'#C6EC6A'});
		$(id).focus();
	},
	ValidateCheckoutForm:function() {		
		var validated = true;				
		var cCardExpired = false;
		var cCardValidated = true;
		
		if($("cardholderName").value.blank()) {
			ShoppingCart.HighlightAndFocus("cardholderName");
			return false;
		}
				
		cCardValidated = ShoppingCart.CheckCardNumber(true);
		cCardExpired = ShoppingCart.CheckCardExpiry();
		
		if(cCardValidated && !cCardExpired) {
			return true;
		} else {
			return false;
		}
	},
	CheckCardNumber:function(focusElement) {
		var validated = true;
		var ccNumber = $("ccNumber").value;
		var ccType = $("cardType").value;
		
		switch(ccType) {
			case "laser":
				if(!CreditCard.IsLaser(ccNumber)) {
					if(focusElement) {
						ShoppingCart.HighlightAndFocus("ccNumber");
					} else {
						new Effect.Highlight("ccNumber",{startcolor:'#C6EC6A'});
					}
					$("ccError").update("Invalid");
					validated=false;
				} else {
					$("ccError").update("&nbsp;");
				}
			break;
			case "visa":
				if(!CreditCard.IsVisa(ccNumber)) {
					if(focusElement) {
						ShoppingCart.HighlightAndFocus("ccNumber");
					} else {
						new Effect.Highlight("ccNumber",{startcolor:'#C6EC6A'});
					}
					$("ccError").update("Invalid");
					validated=false;
				} else {
					$("ccError").update("&nbsp;");
				}
			break;
			case "mastercard":
				if(!CreditCard.IsMasterCard(ccNumber)) {
					if(focusElement) {
						ShoppingCart.HighlightAndFocus("ccNumber");
					} else {
						new Effect.Highlight("ccNumber",{startcolor:'#C6EC6A'});
					}
					$("ccError").update("Invalid");
					validated=false;
				} else {
					$("ccError").update("&nbsp;");
				}
			break;
			case "amex":
				if(!CreditCard.IsAmericanExpress(ccNumber)) {
					if(focusElement) {
						ShoppingCart.HighlightAndFocus("ccNumber");
					} else {
						new Effect.Highlight("ccNumber",{startcolor:'#C6EC6A'});
					}
					$("ccError").update("Invalid");
					validated=false;
				} else {
					$("ccError").update("&nbsp;");
				}
			break;
		}
		return validated;
	},
	CheckCardExpiry:function() {
		var cCardExpired = false;
		var now = new Date();
		var expiryMonth = $("expirationMonth").value;
		var expiryYear = $("expirationYear").value;
		
		if(expiryYear<now.getFullYear()) {
			cCardExpired = true;
		} else {
			if(expiryYear==now.getFullYear() && expiryMonth<now.getMonth()) {
				cCardExpired = true;
			} else {
				cCardExpired = false;
			}
		}
		
		if(cCardExpired) {
			$("edError").update("expired");
			validated=false;
		} else {
			validated=true;
			$("edError").update("&nbsp;");
		}
		return cCardExpired;
	}
}

var CreditCard = {
	IsVisa:function(cc) {
		if(((cc.length == 16) || (cc.length == 13)) && (cc.substring(0,1) == 4)) {
			return CreditCard.IsCreditCard(cc);
		} else {
			 return false;
		}
	},
	IsMasterCard:function(cc) {
		var firstdig = cc.substring(0,1);
		var seconddig = cc.substring(1,2);
		if((cc.length == 16) && (firstdig == 5) && ((seconddig >= 1) && (seconddig <= 5))) {
			return CreditCard.IsCreditCard(cc);
		} else {
			return false;
		}
	},
	IsAmericanExpress:function(cc) {
		var firstdig = cc.substring(0,1);
		var seconddig = cc.substring(1,2);
		if((cc.length == 15) && (firstdig == 3) && ((seconddig == 4) || (seconddig == 7))) {
			return CreditCard.IsCreditCard(cc);
		} else {
			return false;
		}
	},
	IsLaser:function(cc) {
		if((cc.length == 19) && isNumeric(cc)) {
			return true;
		} else {
			return false;
		}
	},
	IsCreditCard:function(st) {
		if(st.length > 19) {
			return false;
		}		
		var sum = 0; 
		var mul = 1; 
		var l = st.length;
		for(i = 0;i<l;i++) {
			digit = st.substring(l-i-1,l-i);
		    tproduct = parseInt(digit ,10)*mul;
		    if (tproduct >= 10) {
		      sum += (tproduct % 10) + 1;
		    } else {
		      sum += tproduct;
			}
		    if(mul == 1) {
		      mul++;
		    } else {
		      mul--;
			}
		}
		
		if((sum % 10) == 0) {
			return true;
		} else {
			return false;
		}
	}
}

String.prototype.isEmail = function () { 
	var rx = new RegExp("\\w+([-+.\’]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*"); 
	var matches = rx.exec(this); 
	return (matches != null && this == matches[0]); 
}

function isNumeric(x) { 
	var y=parseInt(x); 
	if (isNaN(y)) {
	   return false; 
	} else {
		return true;
	}
} 

function checkCourseApplicationForm(){
	var f = document.courseApplicationForm;
	var errMsg = "";
	if( f.userFirstName.value.length < 2 ) errMsg += "\nPlease enter your first name.";
	if( f.userLastName.value.length < 2 ) errMsg += "\nPlease enter your last name.";
	if( f.userPPSNo.value.length < 5 ) errMsg += "\nPlease enter your PPS number.";
	if( f.userMobilePhone.value.length < 10 ) errMsg += "\nPlease enter your mobile phone number (10 digits).";
	if( f.userSchoolName.value.length < 1 ) errMsg += "\nPlease enter your school name.";
	if( f.userSchoolRollNumber.value.length < 1 ) errMsg += "\nPlease enter your school roll number.";
	//if( $("user2ndChoiceCourseId") && f.user2ndChoiceCourseId.selectedIndex == 0 ) errMsg += "\nPlease indicate your second choice.";
	//if( $("user3rdChoiceCourseId") && f.user3rdChoiceCourseId.selectedIndex == 0 ) errMsg += "\nPlease indicate your third choice.";

	if( errMsg != "" ) { alert("Please fix the following problems:\n" + errMsg ); return false; }
	return ShoppingCart.ValidateCheckoutForm();
}

