﻿
function showTip(n) {
    var current = 1;
    var tabs = $$("#tipTabs div");
    
    tabs.each(function(t, i) { if (t.hasClassName("active")) { current += i; t.removeClassName("active"); }});

    $$("#tipTabs div")[n-1].addClassName("active");
    $("tip" + current).hide();
    $("tip" + n).show();
}

/* Send to Friend */

function sendToFriend() {
    if (validateForm())
    {
        var pars = {"senderName" : $F("senderName"),
                    "senderEmail" : $F("senderAddress"),
                    "recipientName" : $F("friendName"),
                    "recipientEmail" : $F("friendAddress"),
                    "msg" : $F("message")}
        var myAjax = new Ajax.Request(
            "SendToFriendService.asmx/SendPage",       //url
            {
                method: "POST",
                parameters: pars,
                onSuccess: mailSent,
                onFailure: sendFailed
            });
    }
}

function validateForm() {
    var valid = true;
    var errorString = "";
    $$(".error").each(function(e) {e.hide() });
    
    if ($F("friendName") == "")
    {
        valid = false;
        errorString += "Friend's name is required\n";
        $("fnError").show();
    }
    if ($F("friendAddress") == "")
    {
        valid = false;
        errorString += "Friend's email is required\n";
        $("feError").show();
    }
//    else if (!validateEmail($F("friendAddress")))
//    {
//        valid = false;
//        errorString += "Friend's email is invalid\n";
//        $("feError").show();
//    }
    if ($F("senderName") == "")
    {
        valid = false;
        errorString += "Your name is required\n";
        $("ynError").show();
    }
    if ($F("senderAddress") == "")
    {
        valid = false;
        errorString += "Your email is required\n";
        $("yeError").show();
    }
//    else if (!validateEmail($F("senderAddress")))
//    {
//        valid = false;
//        errorString += "Your email is invalid\n";
//        $("yeError").show();
//    }
//    
    if (errorString != "") alert(errorString);
    return valid;
}

function validateEmail( strValue) {
	var objRegExp = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/;
	//var objRegExp = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
    //var objRegExp = /^[a-z]([\w-\.])*@[\w-\.]+(\.[\w-\.])*$/i;
    return objRegExp.test(strValue);
}

function clearFields() {
    $("senderName").value = "";
    $("senderAddress").value = "";
    $("friendName").value = "";
    $("friendAddress").value = "";
    $("message").value = "Check out this newsletter from Family-Cents.com";
}

function mailSent(t) {
    $("stfForm").hide();
    $("stfThanks").show();
    clearFields();
}

function sendFailed() {
    $("stfForm").hide();
    $("stfError").show();
}

function openSTF() {
    $("stfError").hide();
    $("stfThanks").hide();
    $("stfForm").show();
    $("stfPanel").show();
}

function closeSTF() {
    $("stfPanel").hide();
}

/* Tip Form */
function submitTip() {
    if (validateTipForm())
    {
        var pars = {"tip_period_nbr" : $F("tip_period_nbr"),
                    "tip_txt" : $F("tipText"),
                    "name_nm" : $F("tipName"),
                    "hometown_nm" : $F("tipTown")}
                    
        var myAjax = new Ajax.Request(
            "TipService.asmx/PostTip",       //url
            {
                method: "POST",
                parameters: pars,
                onSuccess: tipSent,
                onFailure: tipFailed
            });
    }

}
	    
function tipSent(t) {
	$("tipThanks").show();
	$("tipText").value = "";
	$("senderAddress").value = "";
	$("tipName").value = "";
	$("tipTown").value = "";
}

function tipFailed() {
	$("tipErrorMsg").show();
}   
	
function validateTipForm() {
    var valid = true;
    var errorString = "";
    $$(".error").each(function(e) {e.hide() });
    
    if(!$("chkTerms").checked){
        valid = false;
        errorString += "You must accept the terms and conditions\n"; 
    }
    
    if ($F("tipText") == "")
    {
        valid = false;
        errorString += "Tip is required\n";
        //$("tipError").show();
    }
    if ($F("tipName") == "")
    {
        valid = false;
        errorString += "Your name is required\n";
        //$("tipNameError").show();
    }
    if ($F("tipTown") == "")
    {
        valid = false;
        errorString += "Your hometown is required\n";
        //$("tipTownError").show();
    }
    if (errorString != "") alert(errorString);
    return valid;
}	 

function closeTip() {
    $("tipThanks").hide();
    $("tipErrorMsg").hide();
}

/* FROM WHERESYOURS */

//Add event listeners for imgElem to create rollover effect with image at url overSrc on mouseover, and outSrc on mouseout
//imgElem can be image object or id of image object
function addRolloverImage(imgElem, outSrc, overSrc) {
    $(imgElem).observe('mouseover', function(event) { Event.element(event).src = overSrc });
    $(imgElem).observe('mouseout', function(event) { Event.element(event).src = outSrc });
}

//Return true iff browser is Internet Explorer with version less than 7
function isIElt7() {
    return ((/MSIE ((5\.5)|[6])/.test(navigator.userAgent)) && (parseInt(RegExp.$1,10) < 7))
}

//display character count message
/*example usage:
//<input type="text" id="textArea1" onkeyup="checkCharCount('textArea1',10)" />
//<div id="textArea1Count"></div>
*/
function checkCharCount(id){
    var countMessage = " characters used";
    var cctv =      $(id).readAttribute('clientcontroltovalidate');
    var maxlen =    $(id).readAttribute('maxlengthzz');
    var msg =       $(id).readAttribute('lengthmessageid');
    $(msg).innerHTML = $(cctv).value.length + countMessage ;
    if ($(cctv).value.length >= maxlen){
        $(cctv).className = "error";
        return false;
    } else {
        $(cctv).className = "errorCheck";
        return true;
    }
}

function checkEmptyText(id){
    var cctv =  $(id).readAttribute('clientcontroltovalidate');
    //alert('value is ' + $(cctv).value);
    if (($(cctv).value == null) || ($(cctv).value.length == 0)){
        $(cctv).className = "errorForm";
        //new Effect.Appear ($(id), {duration: 1.25});
        return false;
    }
    else
    {
        $(cctv).className = "defaultForm";
        //new Effect.Fade ($(id), {duration: 1.25});
        return true;
    } 
}

//Assumes that the initial value, if there is one, parses to boolean false. "-1" works.
function checkSelected(id){
    var cctv =  $(id).readAttribute('clientcontroltovalidate');
    if (! $(cctv).selectedIndex){
        $(cctv).className = "errorForm";
        //new Effect.Appear ($(errid), {duration: 1.25});
        return false;
    }
    else
    {
        $(cctv).className = "defaultForm";
        //new Effect.Fade ($(errid), {duration: 1});
        return true;
    }
}

function checkNumeric(id){
    var cctv =  $(id).readAttribute('clientcontroltovalidate');
    if ($(cctv).value.length > 0) {
        if (!validateNumeric($(cctv).value)){
            $(cctv).className = "errorForm";
            //new Effect.Appear ($(id), {duration: 1.25});
            return false;
        } else {
            $(cctv).className = "defaultForm";
            //new Effect.Fade ($(id), {duration: 1.25});
            return true;
        }
    }
}

//Returns today's date formatted: Mon DD, YYYY
function formatDate(m, d, y) {
    var months = ['Jan.', 'Feb.', 'Mar.', 'Apr.', 'May', 'June', 'July', 'Aug.', 'Sept.', 'Oct.', 'Nov.', 'Dec.'];
    return months[m-1] + ' ' + d + ', ' + y;
}

/**** Stats Functions *****/

function writeStats() {
    var d=new Date();
    var day=d.getDate();
    var month=d.getMonth() + 1;
    var year=d.getFullYear();
    $('date').innerHTML = formatDate(month, day, year);
    var myAjax = new Ajax.Request(
    'CelebrateService.asmx/GetImageCount',       //url
    {
        method: 'POST',
	    onSuccess: showImageCount
	});
    var myAjax = new Ajax.Request(
    'CelebrateService.asmx/GetProfileCount',       //url
    {
        method: 'POST',
	    onSuccess: showProfileCount
	});
    var myAjax = new Ajax.Request(
    'CelebrateService.asmx/GetPlaceCount',       //url
    {
        method: 'POST',
	    onSuccess: showPlaceCount
	});    		    		
}
function showProfileCount(t){
    var result = t.responseXML.documentElement.firstChild.data;
    $('profiles').innerHTML = result;
}
function showPlaceCount(t){
    var result = t.responseXML.documentElement.firstChild.data;
    $('places').innerHTML = result;
}
function showImageCount(t){
    var result = t.responseXML.documentElement.firstChild.data;
    $('photos').innerHTML = result;
}

function initializeNav(){
   /* var myAjax = new Ajax.Request(
    'wy_promo.js',       //url
    {
        method: 'GET',
        parameters: '',
	    onSuccess: showPromo
	});    	*/	    	
}
function showPromo(t){
    var resultsJSON = t.responseText.evalJSON();
    $("promo").innerHTML = "<a href='"+resultsJSON.promo[0].promo_url+"' class='SignInLnk' target=_blank>"+resultsJSON.promo[0].promo_txt+"</a>";
}

/*
Functions below by:
AUTHOR: Karen Gayda
DATE: 03/24/2000
*/

function validateEmail( strValue) {
/************************************************
DESCRIPTION: Validates that a string contains a
  valid email pattern.

 PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.

REMARKS: Accounts for email with country appended
  does not validate that email contains valid URL
  type (.com, .gov, etc.) or valid country suffix.
*************************************************/
var objRegExp  =
 /(^[a-z]([a-z_\.]*)@([a-z_\.]*)([.][a-z]{3})$)|(^[a-z]([a-z_\.]*)@([a-z_\.]*)(\.[a-z]{3})(\.[a-z]{2})*$)/i;

  //check for valid email
  return objRegExp.test(strValue);
}

function  validateNumeric( strValue ) {
/*****************************************************************
DESCRIPTION: Validates that a string contains only valid numbers.

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
******************************************************************/
  var objRegExp  =  /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/;

  //check for numeric characters
  return objRegExp.test(strValue);
}

function validateInteger( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains only
    valid integer number.

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
**************************************************/
  var objRegExp  = /(^-?\d\d*$)/;

  //check for integer characters
  return objRegExp.test(strValue);
}

function validateNotEmpty( strValue ) {
/************************************************
DESCRIPTION: Validates that a string is not all
  blank (whitespace) characters.

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
*************************************************/
   var strTemp = strValue;
   strTemp = trimAll(strTemp);
   if(strTemp.length > 0){
     return true;
   }
   return false;
}

function trimAll( strValue ) {
/************************************************
DESCRIPTION: Removes leading and trailing spaces.

PARAMETERS: Source string from which spaces will
  be removed;

RETURNS: Source string with whitespaces removed.
*************************************************/
 var objRegExp = /^(\s*)$/;

    //check for all spaces
    if(objRegExp.test(strValue)) {
       strValue = strValue.replace(objRegExp, '');
       if( strValue.length == 0)
          return strValue;
    }

   //check for leading & trailing spaces
   objRegExp = /^(\s*)([\W\w]*)(\b\s*$)/;
   if(objRegExp.test(strValue)) {
       //remove leading and trailing whitespace characters
       strValue = strValue.replace(objRegExp, '$2');
    }
  return strValue;
}

////////////Authenticate//////////////
function si() {
    $("ModalError").innerHTML = "";
    var myAjax = new Ajax.Request(
	    'CelebrateService.asmx/LogIn',       //url
	    {
		    method: 'POST',
		    parameters: 'username='+$("SIun").value+'&password='+$("SIpw").value + '&persistent=false',
		    onSuccess: showSI
		});
}

function showSI(t){
    var test = t.responseXML.documentElement.firstChild.data;
    if (test=="true") {
        window.location = $("SIurl").value;
    } else {
        $("ModalError").innerHTML = "username/password failed";
    }
    
}

/****** Utility Functions ********************************************************/
function toggleDisplay(id) {
    var obj = $(id);
    obj.style.display = (obj.style.display != "none") ? "none" : "";
}

//Toggles visibility of HTML DOM object with id 'id'
function toggleVisibility(id) {
    var obj = $(id);
    obj.style.visibility = (obj.style.visibility == "hidden") ? "visible" : "hidden";
}

function parseImageId(url) {
    return url.substring(url.indexOf("d=")+2,url.indexOf("&"));
}

function openEmailFriend() {
    var w = window.open('EmailFriend.aspx', 'emailfriend', 'height=200,width=400,status=yes,toolbar=no,menubar=no,location=no, scrollbar=no');
}   