$(document).ready(function(){
	//	Sliding buttons
	function setupButtons(){
		var $buttons = $('a.btn-expand');

		$buttons.append('<span class="btn-mask" style="display:none"></span>');
		$buttons.each(function(){
			
			var buttonMask = $('.btn-mask', this);
			var direction = 'right';
			if( $(this).hasClass('slide-left') ){
				direction = 'left';
			}
			
			$(this).hover(
				function(){
					buttonMask.show();
					buttonMask.width( 60 );
					if( direction == 'left' ){
						buttonMask.animate({ 'width' : 0 }, 300);
					} else {
						buttonMask.animate({ 'left' : 60 }, 300);
					}
				},
				function(){
					buttonMask.stop().css('left', 0).hide();
				}
			);
		});
	}
	
	function setupInternalLinks() {
		$('a').live('click', function(ev) {
			if (!$(this).hasClass("external")) {
				var href = $(this).attr('href');
				if (href.match(/^\/virginmobile\/web/)) {
					top.Site.setContent(href.substring(17));
					ev.preventDefault();
				} else if (href.match(/^\//)) {
					top.Site.setContent(href);
					ev.preventDefault();
				}
			}
		});
	}
	
	$('div.right-offer .panel-content').append('<div class="offer-pointer"></div>');
	
	function closePanel(panelToClose){
		$(panelToClose).parents('div.panel').fadeOut(function(){
			var $redeemPanel = $(this).parent();
			if( $redeemPanel.hasClass('always-shown') ){
				$(this).hide();
				$(this).parent().find('div.entry-form').fadeIn();
			} else {
				$(this).hide();
				$(this).parent().hide();
			}
		});
	}
	
	$('div.redeem-panel a.close').click(function(){
		closePanel(this);
		return false;
	});
	
	$('a.btn-offer').click(function(){
		var offerId = $(this).attr('rel');
		var $offerContainer = $('#'+offerId);
		var $offerDetails = $('#'+offerId+' .entry-form');
		var $offerFeedback = $('#'+offerId+' .feedback');
		var $offerRegister = $('#'+offerId+' .register');
		
		if( $offerContainer.is(':visible') ){
			$offerContainer.animate({ height: 0 }, 1000, function(){
				$(this).hide();
			});
		} else {
			$offerFeedback.hide();
			$offerDetails.find('input.terms').removeAttr('checked');
			$offerContainer.css('height', 0).show();
      
      // UPDATE BY BRENDAN. The "Free for all" offer type (offer-type-9) should
      // be shown to all users
			if( parent.Site.isLoggedIn() || $offerContainer.hasClass('free-for-all')){
				$offerRegister.hide();
				$offerDetails.show();
				
				// tracking code
				$.post(pathRoot+'../inc/tracking-process.php', {action:'view_offer', id:offerId, location:document.location.href});
				// end of tracking code
				
				$('#'+offerId+' .feedback .panel-content').height( $('#'+offerId+' .entry-form .panel-content').height() );
				$offerContainer.animate({ height: $offerDetails.height()+15 }, 1000);			
			} else {
				$offerDetails.hide();
				$offerRegister.show();
				$offerContainer.animate({ height: $offerRegister.height()+15 }, 1000);			
			}
		}
		
		return false;
	});
	
	$('a.redeem-login').click(function(e){
		parent.Site.showLoginPanel();
		closePanel(this);
		e.preventDefault();
	});
	
	/* Redeem offer */
	
	function submitForm(form){
		var terms = form.find(".terms");
		if( terms.length > 0 && !terms.is(":checked") ) {
			alert("You must accept the terms and conditions.");
			return false;
		}
		
		var offerId = form.parent().parent().parent().attr('id');
		var $offerContainer = $('#'+offerId);
		var $offerDetails = $('#'+offerId+' .entry-form');
		var $offerFeedback = $('#'+offerId+' .feedback');
		var $submitButton = $('#'+offerId+' .entry-form .btn-enter');
		
		$submitButton.addClass('btn-loading');
		
		var data = form.serialize();
		
		$.getJSON(cp+"/virgin/redeemoffer/redeem_offer.php", data, function(response){ 
			response = response.response;
			if (response.message == "API parameter is missing.")
				response.message = "Please fill in all of the required fields.";
		
			$offerDetails.fadeOut(function(){
				if( response.success == "true" ) {
					// tracking code
				 	$.post(pathRoot+'../inc/tracking-process.php', {action:'redeem_offer', id:offerId, location:document.location.href});
					// end of tracking code
				
					$offerFeedback.find('h2').html('Success');
					$offerFeedback.find('h5').html(response.message);
					Cufon.refresh('.redeem-panel h2');
					Cufon.refresh('.redeem-panel h5');
				} else {
					$offerFeedback.find('h2').html('Failure');
					$offerFeedback.find('h5').html('An error occurred: ' + response.message);
					Cufon.refresh('.redeem-panel h2');
					Cufon.refresh('.redeem-panel h5');
				}
				$offerFeedback.fadeIn();
			});
			$submitButton.removeClass('btn-loading');
		});
		
		return false;
	}
	
	$("div.email-form form").each(function() {
		$(this).validate({
			rules: {
				emailAddress: {
					required: true,
					email: true
				}
			},
			errorElement: "em",
			invalidHandler: function(form, validator) {
				var errors = validator.numberOfInvalids();
				if (errors) {
					var message = 'Please enter a valid email address';
					alert(message);
				}
			},
			highlight: function(element, errorClass) {
				$(element).addClass(errorClass);
			},
			unhighlight: function(element, errorClass) {
				$(element).removeClass(errorClass);
			},
			submitHandler: function(form) {
				submitForm( $(form) );
			}
		});
	});
	
	$("div.details-form form").each(function() {
		$(this).validate({
			rules: {
				firstName: "required",
				lastName: "required",
				emailAddress: {
					required: true,
					email: true
				},
				address1: "required",
				suburb: "required",
				postcode: "required",
				state: "required"
			},
			errorElement: "em",
			invalidHandler: function(form, validator) {
				var errors = validator.numberOfInvalids();
				if (errors) {
					var message = 'Please complete all required fields';
					alert(message);
				}
			},
			highlight: function(element, errorClass) {
				$(element).addClass(errorClass);
			},
			unhighlight: function(element, errorClass) {
				$(element).removeClass(errorClass);
			},
			submitHandler: function(form) {
				submitForm( $(form) );
			}
		});
	});
  
  $("div.free-for-all form").each(function() {
		$(this).validate({
			rules: {
				firstName: "required",
				lastName: "required",
				emailAddress: {
					required: true,
					email: true
				},
        mobileNumber: {
					required: true,
					mobileNumber: true
				},
				address1: "required",
				suburb: "required",
				postcode: "required",
				state: "required"
			},
			errorElement: "em",
			invalidHandler: function(form, validator) {
				var errors = validator.numberOfInvalids();
				if (errors) {
					var message = 'Please complete all required fields';
					alert(message);
				}
			},
			highlight: function(element, errorClass) {
				$(element).addClass(errorClass);
			},
			unhighlight: function(element, errorClass) {
				$(element).removeClass(errorClass);
			},
			submitHandler: function(form) {
				if (form.dobDay != null){
					var d = form.dobDay.value;
			        var m = form.dobMonth.value;
			        var y = form.dobYear.value;
			        
			        if (d < 10) {
			          d = "0" + d;
			        }
			        
			        if (m < 10) {
			          m = "0" + m;
			        }
			        
			        var ds = m + '/' + d + '/' + y;
			        
			        if (isDate(ds) != false) {
			          // over 18 check
			          var dob = new Date(parseInt(form.dobYear.value), parseInt(form.dobMonth.value) - 1, parseInt(form.dobDay.value));
			          var today = new Date();
			          var eighteenYears = 1000 * 60 * 60 * 24 * 6574; // 6574 Days in 18 years
			          var diff = today.getTime() - dob.getTime();
			                   
			          if (diff < eighteenYears) {
			            alert("You must be at least 18 years old to enter");
			          }
			        } else {
			          return false;
			        }
		        }
				if ($("input:radio[name=smirnoffMail]") != null){
					var value = $("input[name=smirnoffMail]:checked").val();
					if (value == null){
						$("input:radio[name=smirnoffMail]").parent().parent().parent().parent().css({border:"1px red solid"});
						alert("select an option for mail");
						return;
					} else {
						$("input:radio[name=smirnoffMail]").parent().parent().parent().parent().css({border:"0px"});
					}
					var value = $("input[name=smirnoffSMS]:checked").val();
					if (value == null){
						$("input:radio[name=smirnoffSMS]").parent().parent().parent().parent().css({border:"1px red solid"});
						alert("select an option for sms");
						return;
					} else {
						$("input:radio[name=smirnoffSMS]").parent().parent().parent().parent().css({border:"0px"});
						submitForm( $(form) );
					}
				}
			}
		});
	});
	$("div.skydive-form form").each(function() {
		$(this).validate({
			rules: {
				firstName: "required",
				lastName: "required",
				emailAddress: {
					required: true,
					email: true
				},
				address1: "required",
				suburb: "required",
				postcode: "required",
				state: "required",
				answer: {
		          required:true,
		          twentyFiveWords:true
		        }
			},
			errorElement: "em",
			invalidHandler: function(form, validator) {
				var errors = validator.numberOfInvalids();
				if (errors) {
					var message = 'Please complete all required fields';
					alert(message);
				}
			},
			highlight: function(element, errorClass) {
				$(element).addClass(errorClass);
			},
			unhighlight: function(element, errorClass) {
				$(element).removeClass(errorClass);
			},
			submitHandler: function(form) {
				submitForm( $(form) );
			}
		});
	});
  $("div.splendour-question-form form").each(function() {
		$(this).validate({
			rules: {
				firstName: "required",
				lastName: "required",
				emailAddress: {
					required: true,
					email: true
				},
				address1: "required",
				suburb: "required",
				postcode: "required",
				state: "required",
        answer: {
          required:true,
          twentyFiveWords:true
        }
			},
			errorElement: "em",
			invalidHandler: function(form, validator) {
        var errors = validator.numberOfInvalids();
				if (errors) {
          if (errors == 1) {
            var message = validator.errorList[0].message;
          } else {
        		var message = 'Please complete all required fields';
					}
          alert(message);
				}
			},
			highlight: function(element, errorClass) {
				$(element).addClass(errorClass);
			},
			unhighlight: function(element, errorClass) {
				$(element).removeClass(errorClass);
			},
			submitHandler: function(form) {
				submitForm( $(form) );
			}
		});
	});
  
  var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
var a = [];
	for (var i = 1; i <= n; i++) {
		a[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {a[i] = 30}
		if (i==2) {a[i] = 29}
   } 
   return a
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	var month=parseInt(strMonth)
	var day=parseInt(strDay)
	var year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		alert("The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date")
		return false
	}
return true
}
  
  $("div.smirnoff-form form").each(function() {
		$(this).validate({
			rules: {
				firstName: "required",
				lastName: "required",
				emailAddress: {
					required: true,
					email: true
				},
        mobileNumber: {
					required: true,
					mobileNumber: true
				},
				address1: "required",
				suburb: "required",
				postcode: "required",
				state: "required"
			},
			errorElement: "em",
			invalidHandler: function(form, validator) {
				var errors = validator.numberOfInvalids();
				if (errors) {
					var message = 'Please complete all required fields';
					alert(message);
				}
			},
			highlight: function(element, errorClass) {
				$(element).addClass(errorClass);
			},
			unhighlight: function(element, errorClass) {
				$(element).removeClass(errorClass);
			},
			submitHandler: function(form) {
        var d = form.dobDay.value;
        var m = form.dobMonth.value;
        var y = form.dobYear.value;
        
        if (d < 10) {
          d = "0" + d;
        }
        
        if (m < 10) {
          m = "0" + m;
        }
        
        var ds = m + '/' + d + '/' + y;
        
        if (isDate(ds) != false) {
          // over 18 check
          var dob = new Date(parseInt(form.dobYear.value), parseInt(form.dobMonth.value) - 1, parseInt(form.dobDay.value));
          var today = new Date();
          var eighteenYears = 1000 * 60 * 60 * 24 * 6574; // 6574 Days in 18 years
          var diff = today.getTime() - dob.getTime();
                   
          if (diff < eighteenYears) {
            alert("You must be at least 18 years old to enter");
          } else {
            submitForm( $(form) );
          }
        } else {
          return false;
        }
			}
		});
	});
  
	// Custom australian mobile number validator
	jQuery.validator.addMethod("mobileNumber", function(value, element) {
		return String(value).match(/^04[0-9]{8}$/) != null;
	}, 'Please enter a valid mobile number');
	
  // Custom 25 words or less validator
  jQuery.validator.addMethod("twentyFiveWords", function(value, element) {
    var arr = value.split(" ");
    
    return arr.length <= 25;
		
	}, 'Your answer needs to be 25 words or less');
  
	jQuery.validator.addMethod("auNumber", function(value, element) {
		if (value.indexOf('04') == 0) {
			return String(value).match(/^04[0-9]{8}$/) != null;
		}
		
		return String(value).match(/(^1300\d{6}$)|(^1800|1900|1902\d{6}$)|(^0[2|3|7|8]{1}[0-9]{8}$)|(^13\d{4}$)|(^04\d{2,3}\d{6}$)/) != null;		
	}, 'Please enter a valid australian phone number');
	
	
	$("div.sms-form form").each(function(){
		$(this).validate({
			rules: {
				mobileNumber: {
					required: true,
					mobileNumber: true
				}
			},
			errorElement: "em",
			invalidHandler: function(form, validator) {
				var errors = validator.numberOfInvalids();
				if (errors) {
					var message = 'Please enter a valid mobile number';
					alert(message);
				}
			},
			highlight: function(element, errorClass) {
				$(element).addClass(errorClass);
			},
			unhighlight: function(element, errorClass) {
				$(element).removeClass(errorClass);
			},
			submitHandler: function(form) {
				submitForm( $(form) );
			}
		});
	});
		
	$('div.member-signup-form form').submit(function(e){
		var optin = $(this).find(".optin");
		if( optin.length > 0 && !optin.is(":checked") ) {
			alert("You must agree to receive communications on the latest news and handset deals from Virgin Mobile.");
			e.preventDefault();
			return false;
		}

		var offerId = $(this).parent().parent().parent().attr('id');
		var $offerContainer = $('#'+offerId);
		var $offerDetails = $('#'+offerId+' .member-signup-form');
		var $offerFeedback = $('#'+offerId+' .feedback');
		var $submitButton = $('#'+offerId+' .member-signup-form .btn-submit');
		
		$submitButton.addClass('btn-loading');
		
		this.elements['expiryDate'].value = this.elements['expiryDateMonth'].value + "/" + this.elements['expiryDateYear'].value;
		var data = $(this).serialize();
		
		$.getJSON(cp+"/virgin/prospect/add_prospect.php", data, function(response){ 
			response = response.response;
			if (response.message == "API parameter is missing.")
				response.message = "Please fill in all of the required fields.";
			
			$offerDetails.fadeOut(function(){
				// Show the relevant message depending on what happened
				if( response.success == "true" ) {
					$offerFeedback.find('h5').html(response.message);
				} else {
					$offerFeedback.find('h2').html('Failure');
					$offerFeedback.find('h5').html('An error occurred: ' + response.message);
					Cufon.refresh('.redeem-panel h2');
					Cufon.refresh('.redeem-panel h5');
				}
				$offerFeedback.fadeIn();
			});
			$submitButton.removeClass('btn-loading');
		});
		
		return false;
	});
	
	$('a[rel="popup"]').click(function(){
		var link = $(this).attr('href');
		day = new Date();
		id = day.getTime();
		window.open(link,id,'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=700,height=650');
		return false;
	});
	
	Cufon.replace('.redeem-panel h2', { fontFamily: 'OmnesBldIta', fontWeight: '700' });
	Cufon.replace('.redeem-panel h5', { fontFamily: 'OmnesSemBldIta', fontWeight: '600' });
	Cufon.replace('.twitter-panel h2', { fontFamily: 'OmnesBldIta', fontWeight: '700' });
	Cufon.replace('.offer h4', { fontFamily: 'OmnesSemBldIta', fontWeight: '600', fontSize: '16px' });
	Cufon.replace('.offer p[class!="button"]', { fontFamily: 'OmnesSemBldIta', fontWeight: '600', fontSize: '13px' });
	Cufon.replace('.twitter-follow p', { fontFamily: 'OmnesSemBldIta', fontWeight: '600' });
	Cufon.replace('.twitter-status p', { fontFamily: 'OmnesSemBldIta', fontWeight: '600' });
	Cufon.replace('.actions p strong', { fontFamily: 'OmnesBldIta', fontWeight: '700', fontSize: '15px' });
	
	setupButtons();
	setupInternalLinks();
	
});

function setSection(sectionName, cp, articleId, articleTitle, categoryId, categoryTitle) {
	if (top.Site != undefined) {
		// tracking code
			if (articleId != ""){
				$.post(pathRoot+'../inc/tracking-process.php', {action:'View Article', id:articleId, title:articleTitle, location:document.location.href});
			} else {
				$.post(pathRoot+'../inc/tracking-process.php', {action:'View Category', id:categoryId, title:categoryTitle, location:document.location.href});
			}
			// end of tracking code
		top.Site.setSection(sectionName);
	} else {
		var newLocation;
		if (location.pathname.match(/^\/virginmobile\/web\//)) {
			/* For dev */
			newLocation = cp + "/#" + location.pathname.replace(/^\/virginmobile\/web/, "");
		} else if (location.pathname.match(/^\/virginmobile\//)) {
			/* For dev */
			newLocation = cp + "/#" + location.pathname.replace(/^\/virginmobile/, "");
		} else {
			newLocation = cp + "/#" + location.pathname;
		}

		setTimeout(function() {
			top.location = newLocation;
		}, 1000);
	}
}