/* 
 * Returns true if a numeric, slash or control key was pressed
 * @argument evt The key event
 */
function vp_checkDateKey(evt) {
    return vp_validateChars(evt, "0123456789/", true);
}


/* 
 * Initial cap first letter of each word
 * @argument str The str to convert
 */
function cnvrt2Upper(str) {
	function cnvrt() {
		return arguments[0].toUpperCase();
	}
	return str.toLowerCase().replace(/\b[a-z]/g, cnvrt);
}


/* 
 * Validate that a required field is not empty
 * @argument field The id of the field
 * @argument errorDiv The id of the error div (for error messages)
 * @argument fieldName The name of the field to appear in the error message
 */ 
function vp_validateEmpty(field, msg) {
    var str = vp_trimStr($(field).val());
    if ((str === null) || (str.length === 0)) {
        $(field + "Error").html(msg);
    }
    else {
        $(field + "Error").html('');
    }
}

/* 
 * Validate Geo Search
 */
function vp_validateGeoSearch() {
	var geo = vp_trimStr($("#geo").val());
	
	if (geo == 'City, State/Province -or- ZIP/Postal Code' || geo == 'City, State -or- ZIP Code' || geo == '') {
		// No geo entered
		$("#geoError").html('City, State/Province or ZIP/Postal Code Required').show();
		$("#geo").focus();
		return false;
	}
	
	var locationGeo = $("#geo").val();
	var geoURL = '/coupons/svc/validate/location';
	g_ajaxErrors = false;
	
	$.ajax({
		url: geoURL,
		dataType: "json",
		data: "geo=" + locationGeo,
		async: false,
		cache: false,
		success: function(data) {
			var chkStatus = data.status;
			var content = data.content;
			
			if (chkStatus == "ok") {
				$("#geoError").hide();
				$.cookie("findingmethod","Geo Search", { path: "/" });
				$.cookie("geo",locationGeo.toLowerCase(), { path: "/" });
				$.cookie("radius",g_radius, { path: "/" });
				// Loader message
				vp_loader();
			}
			else {
				$("#geoError").html(content).show();
				g_ajaxErrors = true;
				$("#geo").focus();
			}
		}
	});
	
	if (g_ajaxErrors) {
		g_ajaxErrors = false; // Reset for subsequent calls
		return false;
	}
}

/* 
 * Validate Keyword Search
 */
function vp_validateKeywords() {
	var kw = vp_trimStr($("#keywords").val());
	
	if (kw == 'Company, product or service' || kw == '') {
		// No keywords entered
		$("#keywordsError").html("Keyword(s) Required").show();
		$("#keywords").focus();
		return false;
	}

	// Remove characters that cause errors for AJAX to submit the form.
	kw = kw.replace(/[\}\{\\|'&#^=]/g, "");
	
	// AJAX validation
	var kwUrl = '/coupons/svc/validate/keywords';
	g_ajaxErrors = false;
	
	// For Omniture, we do not want encoded characters (i.e. %20 for space)
	//	which the escape function will insert
	var kwOmniture = kw.toLowerCase();
	
	// Escape special characters for IE to work.
	kw = escape(kw);
	
	$.ajax({
		url: kwUrl,
		dataType: "json",
		data: "keywords=" + kw,
		async: false,
		cache: false,
		success: function(data) {
			var chkStatus = data.status;
			var content = data.content;
			
			if (chkStatus == "ok") {
				$("#keywordsError").hide();
				$.cookie("findingmethod","Keyword Search", { path: "/" });
				$.cookie("keywords",kwOmniture, { path: "/" });
				// Loader message
				vp_loader();
			}
			else {
				$("#keywordsError").html(content).show();
				g_ajaxErrors = true;
				$("#keywords").focus();
			}
		}
	});
	
	if (g_ajaxErrors) {
		g_ajaxErrors = false; // Reset for subsequent calls
		return false;
	}
}

function vp_validateProfile() {
	if ($("#mobileNumber").val() != 0 && $("#mobileOptIn").val() == 0) {
		$("#mobileError").html('You must opt-in by selecting the box below');
		
		// Restore submit button
		vp_restoreBtn();
		
		return false;
	}
	else {
		$("#mobileError").html('');
	}
}

/* 
 * Process an RSS geography validation response
 * @argument msg The message from the server
 * @argument geo The new geography
 */ 
function vp_submitRSS() {
    var geo = vp_trimStr($("#geo").val());
	
	if (geo == 'City, State/Province -or- ZIP/Postal Code' || geo == '') {
		// No geo entered
		$("#geoError").html('City, State/Province or ZIP/Postal Code Required').show();
		$("#geo").focus();
		return false;
	}
	
	var locationGeo = $("#geo").val();
	var geoURL = '/coupons/svc/validate/location';
	g_ajaxErrors = false;
	
	$.ajax({
		url: geoURL,
		dataType: "json",
		data: "geo=" + locationGeo,
		async: false,
		cache: false,
		success: function(data) {
			var chkStatus = data.status;
			var content = data.content;
			
			if (chkStatus == "ok") {
				$("#geoError").hide();
				return false;
			}
			else {
				$("#geoError").html(content).show();
				g_ajaxErrors = true;
				$("#geo").focus();
			}
		}
	});
	
	if (g_ajaxErrors) {
		g_ajaxErrors = false; // Reset for subsequent calls
		return false;
	}
    
	var geo = $("#geo").val();
    var suffix = "";
    var strArray = geo.split(",");
    if (strArray.length == 1) {
        suffix = "/" + vp_trimStr(strArray[0]);
        // Update coupon header
        $("#couponHeader").html("2. Select Your Coupons for zip/postal code " + strArray[0]);
    }
    else {
        suffix = "/" + vp_trimStr(strArray[0]) + "/" + vp_trimStr(strArray[1]);
        var geoUL = strArray[0] + ", " + strArray[1];
        geoUL = cnvrt2Upper(geoUL);
        // Update coupon header
        $("#couponHeader").html("2. Select Your Coupons for " + geoUL);
    }
    var url = "http://" + location.host + "/coupons/rss/";
    
    // Change mpo links
    $("#google111").attr({target:"_blank", href:"http://fusion.google.com/add?feedurl=" + url + "Groceries" + suffix});
    $("#msn111").attr({target:"_blank", href:"http://my.msn.com/addtomymsn.armx?id=rss&ut=" + url + "Groceries" + suffix});
    $("#yahoo111").attr({target:"_blank", href:"http://add.my.yahoo.com/rss?url=" + url + "Groceries" + suffix});
    $("#couponInput").val(url + "Groceries" + suffix);
    // Change mpo images
    $("#googleImg").attr("src", "/8/d/img/google.gif");
    $("#msnImg").attr("src", "/8/d/img/mymsn.gif");
    $("#yahooImg").attr("src", "/8/d/img/myyahoo.gif");
    $("#couponImg").attr("src", "/8/d/img/coupons.gif");
    
    // Change category links and images
    for (var i = 101; i <= 110; i++) {
        if (i != 105) {
            if (i == 101) {var catname = "Automotive";}
            if (i == 102) {var catname = "Health";}
            if (i == 103) {var catname = "Personal-Care";}
            if (i == 104) {var catname = "Home-and-Office";}
            if (i == 106) {var catname = "Services";}
            if (i == 107) {var catname = "Shops";}
            if (i == 108) {var catname = "Restaurants";}
            if (i == 109) {var catname = "General";}
            if (i == 110) {var catname = "Entertainment-and-Travel";}
            // Change links
            $("#googleCat" + i).attr({target:"_blank", href:"http://fusion.google.com/add?feedurl=" + url + catname + suffix});
            $("#yahooCat" + i).attr({target:"_blank", href:"http://add.my.yahoo.com/rss?url=" + url + catname + suffix});
            $("#msnCat" + i).attr({target:"_blank", href:"http://my.msn.com/addtomymsn.armx?id=rss&ut=" + url + catname + suffix});
            $("#couponInput" + i).val(url + catname + suffix);
            // Change images
            $("#googleImg" + i).attr("src", "/8/d/img/google.gif");
            $("#msnImg" + i).attr("src", "/8/d/img/mymsn.gif");
            $("#yahooImg" + i).attr("src", "/8/d/img/myyahoo.gif");
            $("#couponImg" + i).attr("src", "/8/d/img/coupons.gif");
        }
    }
	
	// Setup aggregator toggle
	$(".aggregator").toggle(
		function() {
			$(this).parent().find('.rssFeed').css({visibility:'visible'}).select();
		},
		function() {
			$(this).parent().find('.rssFeed').css({visibility:'hidden'});
		}
	);
	return false;
}

// Contact us form
function submitContact() {
	var cName = document.getElementById("contactName").value;
	var cEmail = document.getElementById("contactEmail").value;
	var cPostalCode = document.getElementById("contactPostalCode").value;
	var cQuestion = document.getElementById("contactQuestion").value;
	var eType = document.getElementById("emailType").value;
	
	// submit
	setTimeout(function() {
		$.post('/coupons/email', {contactName: cName, contactEmail: cEmail, contactPostalCode: cPostalCode, contactQuestion: cQuestion, emailType: eType}, function(data) {
			$("#dialog-content").html(data);
		});
	},200);
}

