// JavaScript Document

//Combine mobile phone and DOB fields
function vp_combineFields(jqForm, options) {
	vp_combinePhone('mobile');
	vp_combineDOB('dob');
}

//Combine mobile phone fields
function vp_combinePhone(type) {
	if ($("#" + type + "1").val() != "" && $("#" + type + "2").val() != "" && $("#" + type + "3").val() != "") {
		$("#" + type + "Number").val($("#" + type + "1").val() + $("#" + type + "2").val() + $("#" + type + "3").val());
	}
	else {
		$("#" + type + "Number").val(0);
	}
}

//Combine dob fields
function vp_combineDOB(type) {
	var dobMonth = $("#" + type + "Month").val();
	var dobDay = $("#" + type + "Day").val();
	var dobYear = $("#" + type + "Year").val();
	
	if (dobMonth != "" && dobDay != "" && dobYear != "") {
		$("#dateOfBirth").val(dobMonth + "/" + dobDay + "/" + dobYear);
	}
	else {
		$("#dateOfBirth").val("01/01/1900");
	}
}

//Parse phone fields
function vp_parsePhone(type) {
	if (type == 'mobile') {
		g_mobileNum = $("#mobileNumber").val();
		
		var phoneNumPart = new Array (g_mobileNum.substring(0,3), g_mobileNum.substring(3,6), g_mobileNum.substring(6,10));
	}
	if (type == 'phone') {
		g_phoneNum = $("#phoneNumber").val();
		var phoneNumPart = new Array (g_phoneNum.substring(0,3), g_phoneNum.substring(3,6), g_phoneNum.substring(6,10));
	}
	
	if ($("#" + type + "Number").val() != 0) {
		$("#" + type + "1").val(phoneNumPart[0]);
		$("#" + type + "2").val(phoneNumPart[1]);
		$("#" + type + "3").val(phoneNumPart[2]);
	}
}

//Parse dob fields
function vp_parseDOB(type) {
	var dob = $("#dateOfBirth").val();
	var dobPart = dob.split("/");

	$("#" + type + "Month").val(dobPart[0]);
	$("#" + type + "Day").val(dobPart[1]);
	$("#" + type + "Year").val(dobPart[2]);
}

/* 
* Returns true if a numeric or control key was pressed
* @argument evt The key event
*/
//CR 7624 fix donot allow %,.,' in phone number field
function vp_checkNumericKey(evt) {
	var charCode;
	   if(window.event) {
	       charCode = evt.keyCode; // IE
	   }
	   else if(evt.which) {
	       charCode = evt.which; // Netscape/Firefox/Opera
	   }
	if (charCode!=8){ //if the key isn't the backspace key (which we should allow)
		if (charCode<48||charCode>57) //if not a number
		return false; //disable key press
		}
	else 
		return true;
   //return vp_validateChars(evt, "0123456789", true);
}


/* 
* Validates that a key against a list of characters.
* Control characters are always allowed. Note - onkeypress event should be used.
* @argument evt The key event
* @argument strList A list of characters to validate against
* @argument strAllow If true, then only allow what is in strList.
* If false, then do not allow what is in strList.
* @return True if the validation passed, false otherwise.
*/
function vp_validateChars(evt, strList, strAllow) {
   var charCode;
   if(window.event) {
       charCode = evt.keyCode; // IE
   }
   else if(evt.which) {
       charCode = evt.which; // Netscape/Firefox/Opera
   }

   var strChar = String.fromCharCode(charCode);
   if (strAllow === true) {
       // Whitelist check
       if (evt.shiftKey!=1 && (charCode==8 || charCode==9 || charCode==37 || charCode==39 || charCode==46 ||
           charCode==116 || (strList.indexOf(strChar)!= -1))) {
           return true;
       }
       else {
           return false;
       }
   }
   else {
       // Blacklist check
       if (charCode==8 || charCode==9 || charCode==37 || charCode==39 || charCode==46 ||
           charCode==116 || (strList.indexOf(strChar)==-1)) {
           return true;
       }
       else {
           return false;
       }
   }
}

/* 
* Remove leading and trailing spaces from a string
* @argument str The string to trim
* @return The trimmed string
*/ 
function vp_trimStr(str) {
   if (str.charAt(0) == " ") {
       str = vp_trimStr(str.substring(1));
   }
   if (str.charAt(str.length-1) == " ") {
       str = vp_trimStr(str.substring(0,str.length-1));
   }
   return str;
}

/*
* Loading Message for buttons
* @argument btn The button
* @argument msg The optional loading message - default is 'Processing'
*/
function vp_loaderBtn(btn, msg) {
   var message = 'Processing';
	if ($(btn).hasClass('gobtn')) {
		return;
	}
	if ($(btn).hasClass('locsearchbtn')) {
		return;
	}
	if (msg) {message = msg;}
	
	// Remember last button
	g_lastBtn = $(btn);
	g_lastBtnText = $(btn).html();
	
	// Update button with loading message & disable
	$(btn).html(message).addClass('loading').attr({disabled:'disabled'});
}

/*
* Display a daughter window for driving directions
* from the member address to an address of a slug
* @argument slugId The slug id
* @argument addressId The address id
*/
function vp_directions(slugId, addressId) {
   var URL = g_context + '/svc/vpsession/getDirections';
	$.ajax({
		url: URL,
		dataType: "json",
		data: "slugId=" + slugId + "&addressId=" + addressId,
		cache: false,
		success: function(data) {
			var chkStatus = data.status;
			var url = data.content;
			
			if (chkStatus == "ok") {
				if (typeof g_isMobile != "undefined" && g_isMobile != null && g_isMobile) {
					if (confirm("Leaving website.  Continue?")) {
						vp_noDaughter(url);
					}					
				}
				else {
					vp_openWindow(url,'googleDirections',780,580);
				}
			}
		}
	});
}

/*
* Display a daughter window for driving directions
* from the member address to an address of a slug
* @argument slugId The slug id
* @argument addressId The address id
*/
function vp_directionsNoAddressId(override, dStreet, dCity, dState, dZip, sStreet, sCity, sState, sZip) {
	var URL = g_context + '/svc/vpsession/getDirectionsNoAddressId';
	if (override) {
		URL = '/coupons/svc/vpsession/getDirectionsNoAddressId';
	}
	
	var buildData = "dStreet=" + dStreet + "&dCity=" + dCity + "&dState=" + dState + "&dZip=" + dZip;
	if (sStreet != null && sCity != null && sState != null && sZip != null) {
		buildData += "&sStreet=" + sStreet + "&sCity=" + sCity + "&sState=" + sState + "&sZip=" + sZip;
	}
	
	$.ajax({
		url: URL,
		dataType: "json",
		data: buildData,
		cache: false,
		success: function(data) {
			var chkStatus = data.status;
			var url = data.content;
			
			if (chkStatus == "ok") {
				if (typeof g_isMobile != "undefined" && g_isMobile != null && g_isMobile) {
					if (confirm("Leaving website.  Continue?")) {
						vp_noDaughter(url);
					}					
				}
				else {
					vp_openWindow(url,'googleDirections',780,580);
				}
			}
		}
	});
}

/* 
* Window Formatting
* defaults: width-650px height-450px window name-win
*/
function vp_openWindow(path,winName,w,h) {
	window.name="parentWindow";
	if (w == null) {w = 700;} if (h == null) {h = 500;} if (winName == null) {winName = 'win';}
	msgWindow=window.open(path,winName,"menubar=yes,width="+w+",height="+h+",resizable=yes,toolbar=yes,scrollbars=yes,status=yes,screenX=50,screenY=50");
	if (msgWindow != null) {msgWindow.focus();}
}
//Image Window Formatting
function vp_openImgWindow(path,winName,w,h) {
	window.name="parentWindow";
	if (w == null) {w = 650;} if (h == null) {h = 450;} if (winName == null) {winName = 'win';}
	msgWindow=window.open(path,winName,"menubar=no,width="+w+",height="+h+",resizable=yes,toolbar=no,scrollbars=yes,status=yes,screenX=50,screenY=50");
	if (msgWindow != null) {msgWindow.focus();}
}
//No daughter window
function vp_noDaughter(path) {
   window.location=path;
}

var emailOptInOrigVal = 0;
var mobileOptInOrigVal = 0;
var optInOrigVal = 0;
function initCheckboxes(type) {
	$('input[type="checkbox"]:checked').each(function(index) {
        $(this).next().addClass('checked').attr({checked:''});
    });
	
	if (type == 'vpOptins') {
		$(".agree_terms").addClass('agreecheckboxactive');
		$(".agree_terms span, .agree_terms p").click(function(e) {
			if ($(this).prev().attr('id') == 'emailOptIn' ||
				$(this).prev().prev().attr('id') == 'emailOptIn') {
				optInOrigVal = emailOptInOrigVal;
			}
			if ($(this).prev().attr('id') == 'mobileOptIn' ||
				$(this).prev().prev().attr('id') == 'mobileOptIn') {
				optInOrigVal = mobileOptInOrigVal;
			}
			
			if (($(e.target).is('span')) && ($(this).hasClass('checked'))) {
				$(this).removeClass('checked');
				$(this).prev().attr({checked:''});
				$(this).prev().val(0);
			}
			else if (($(e.target).is('span')) && (!($(this).hasClass('checked')))) {
				$(this).addClass('checked');
				$(this).prev().attr({checked:'checked'});
				if (optInOrigVal == '0') {
					$(this).prev().val(2);
				}
				else {
					$(this).prev().val(optInOrigVal);
				}
			}
			else if (($(e.target).is('p')) && (!($(this).prev().hasClass('checked')))) {
				$(this).prev().addClass('checked'); 
				$(this).prev().prev().attr({checked:'checked'});
				if (optInOrigVal == '0') {
					$(this).prev().prev().val(2);
				}
				else {
					$(this).prev().prev().val(optInOrigVal);
				}
			}
			else if (($(e.target).is('p')) && (($(this).prev().hasClass('checked')))) {
				$(this).prev().removeClass('checked'); 
				$(this).prev().prev().attr({checked:''});
				$(this).prev().prev().val(0);
			}
		});
	}
	else {
		$(".agree_terms2").addClass('agreecheckboxactive');
		$(".agree_terms2 span, .agree_terms2 p").click(function(e) {
			if (($(e.target).is('span')) && ($(this).hasClass('checked'))) {
				$(this).removeClass('checked');
				$(this).prev().attr({checked:''});
				$(this).prev().val(false);
			}
			else if (($(e.target).is('span')) && (!($(this).hasClass('checked')))) {
				$(this).addClass('checked');
				$(this).prev().attr({checked:'checked'});
				$(this).prev().val(true);
			}
			else if (($(e.target).is('p')) && (!($(this).prev().hasClass('checked')))) {
				$(this).prev().addClass('checked'); 
				$(this).prev().prev().attr({checked:'checked'});
				$(this).prev().prev().val(true);
			}
			else if (($(e.target).is('p')) && (($(this).prev().hasClass('checked')))) {
				$(this).prev().removeClass('checked'); 
				$(this).prev().prev().attr({checked:''});
				$(this).prev().prev().val(false);
			}
		});
	}
}

function vp_AutoDetectGeo(process)
{
	$.geo("locate",function(position){
		vp_initializeAutoDetectGeo(position.coords.latitude, position.coords.longitude, process);
	},
	function(error, message){
		//$("#currentLocation").html("Current location could not be determined.");
		if(process == "currentAddress")
		{
			alert("Sorry we couldn't determine your current location.");
		}
	});
}

function vp_initializeAutoDetectGeo(lat, lng, process) {
    var latlng = new google.maps.LatLng(lat, lng);
    vp_getGeocoderResults(latlng, process);
}

function vp_getGeocoderResults(latlng, process)
{
	g_geocoder = new google.maps.Geocoder();
	g_geocoder.geocode({'latLng': latlng}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (results != null && results.length > 0) {
        	vp_processGeocoderResults(results, process);        	
        }
      } else {
    	  if(process == "currentAddress")
    	  {
    		  alert("Sorry we couldn't determine your current location.");
    	  }
      }
    });
}	

function vp_processGeocoderResults(results, process)
{
	if(process == "queryGeo")
	{
		vp_processGeocoderResultForCityStateZipCode(results);
	}
	else if (process == "currentAddress")
	{
		//vp_processGeocoderResultForCurrentLocation(results);
		vp_processGeocoderResultForCityStateZipCode(results);
	}
	else if (process == "getDirections")
	{
		vp_processGeocoderResultForGetDirections(results);
	}
}
	
function vp_processGeocoderResultForCityStateZipCode(results)
{    
    var zipCode = "";
    var city = "";
    var state = "";
   	for(var i=0; i < results.length; i++)
 		{
   		var myArray = results[i].formatted_address.split(", ");
   		if(myArray.length == 4)
		{
			// This is a full address.
			//275-291 Bedford Ave, Brooklyn, NY 11211, USA
			// City is in piece #2
			if(city == "")
		    {
		    	city = myArray[1];
		    }
			//State and Zip is in piece #3
			var stateZipArray = myArray[2].split(" ");
			if(state == "" && stateZipArray[0].length == 2)
	    	{
	    		state = stateZipArray[0];
	    	}
			if(zipCode == "")
			{
				zipCode = stateZipArray[1];
			}
			break;
		}
   		else
		{    			
			if (myArray.length == 3)
		    {
		    	//Williamsburg, NY, USA
		    	//Kings, New York, USA
		    	//Brooklyn, New York, USA
		    	//New York, New York, USA
		    	
		        // Piece #1 should have the city
		        // Piece #2 should have the state
		        if(city == "")
		        {
		        	city = myArray[0];
		        }
					
		    	if(state == "" && myArray[1].length == 2)
		    	{
		    		state = myArray[1];
		    	}
		    }
		    else if (myArray.length == 2)
	    	{
		    	//New York 11211, USA
				//State and Zip is in piece #1
				var stateZipArray = myArray[0].split(" ");
		    	if(state == "" && stateZipArray[0].length == 2)
		    	{
	    			state = stateZipArray[0];
		    	}
				if(zipCode == "")
				{
					zipCode = stateZipArray[1];
				}
	    	}
		}
   	}
   
    //alert("city, state = " + city + ", " + state + " and zipCode = " + zipCode);
    if(city != '' && state != '')
   	{
    	$("#geo").val(city + ", " + state);
   	}
    else if (zipCode != '')
   	{
    	$("#geo").val(zipCode);
   	}
}

function vp_processGeocoderResultForCurrentLocation(results)
{    
   	for(var i=0; i < results.length; i++)
	{
   		var myArray = results[i].formatted_address.split(", ");
   		if(myArray.length == 4)
		{
			// This is a full address.
			//275-291 Bedford Ave, Brooklyn, NY 11211, USA
			$("#currentLocation").html(results[i].formatted_address);
			break;
		}
   		else
		{    			
   			alert("Sorry we couldn't determine your current location.");
		}
   	}
}

var directionsArray;
function vp_processGeocoderResultForGetDirections(results)
{    
	directionsArray = null; // Clear it out
	var fullAddressFound = false;
	for(var i=0; i < results.length; i++)
	{
		directionsArray = results[i].formatted_address.split(", ");
   		if(directionsArray.length == 4)
		{
			// This is a full address.
			//275-291 Bedford Ave, Brooklyn, NY 11211, USA
			break;
		}
   	}
}

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

/* 
 * Not me?
 * Clears the cookies and take the user to the welcome page.
 */
function vp_notMe() {
	// Remove cookies
	$.cookie('JSESSIONID',null,{path: '/coupons'});
	$.cookie('JSESSIONID',null,{path: '/'});
	$.cookie('_COUPONS_ONLINE',null,{path: '/'});
	$.cookie('VALPAK_ZIP8',null,{path: '/'});
	$.cookie('UA',null,{path: '/'});
	// Go to the home page.  In this case, the welcome page.
	
	var url = null;
	if (g_context == "/coupons"){
		url = 'http://' + document.location.host + g_context + '/home';
	} else {
		url = g_context + '/home';
	}
	window.location = url;
}

/* 
 * Reminder Opt-in (on the contest registration page)
 */
function vp_optInReminder(userid) {
	var ocoURL = g_context + '/svc/member/optInMember';
	
	$.ajax({
		url: ocoURL,
		dataType: "json",
		data: "userId=" + userid,
		cache: false,
		success: function(data){
			 $("#remText").html('<b style="color:#2D4C9C">Your confirmation email has been resent. Just click the link in the email to become eligible for all your Valpak.com Exclusives!</b>');
		}
	});
}

/*
 * Code for the Facebook/Twitter Share Additional Contest Entries 
 */
function vp_submitAdditionalInclusionEntries(contestId, additionalEntries) {
	if( document.getElementById('tafResultsMessage') != null && document.getElementById('confirmationMessage') != null )
	{
		htmlStr = $('#confirmationMessage').html();
		$('#tafResultsMessage').html(htmlStr);
	}
	$('#FBTshare').hide();
	
	var URL = g_context + '/svc/contest/saveAdditionalEntries';
	
	$.ajax({
		url: URL,
		dataType: "json",
		data: "contestId=" + contestId,
		cache: false,
		success: function(data) {
			var chkStatus = data.status;
			var content = data.content;
			
			if (chkStatus == "ok") {
				$("#contestRegData").html(data.content);
			}
		}
	});
	
	/*if (additionalEntries > 0) {
		ContestReg.saveAdditionalInclusionEntries(contestId);
		// Clear AJAX error stack
		_vpContestErrors.clearAll();
	}*/
	return false;
}

function contestModalDocument(contentURL) {
	$("#dialog-content #content").load(contentURL);
}

