/* account.js */
$(document).ready(function() {
    if ($("#account-template").length) {
        BenefulMap.userAccountTabs("#account-tabs #user-account-tabs", ".user-account-sort", 3);
        BenefulMap.setupEditSpotAccountModal();
        var els = {
            modalDiv: "#modal-confirm-removal",
            targetElement: "a.remove"
        };
        var newModal = new BenefulMap.ModalConfirmRemoval("Confirm Removal", els, {}, root + "Snippets/Account/ConfirmRemoval.aspx", {});
        BenefulMap.setUpFullSizePicModal();

        if ($("#edit-wag-world-profile").length) {
            embedFlash();
            populateNicknameOnLoad();
        }
        BenefulMap.loggedInLinks();
    }
});

BenefulMap.routeEditFormToPostBack = function() {
	$("#edit-wag-world-profile").keypress(function(event) {
		if (event.which == 13) {
			$("#edit-wag-world-profile input:image").click();
		}
	});
}

BenefulMap.setUpFullSizePicModal = function() {
	var els = {
		modalDiv: "#modal-full-size",
		targetElement: "a.photo-link" 
	};
	var initialParams = {
		id: 0
	}
	var newModal = new BenefulMap.ModalFullSizePhoto("Photo", els, initialParams, BenefulMap.Constants.Snippets.MODAL_FULL_SIZE_PHOTO, {});
}


BenefulMap.setupEditSpotAccountModal = function() {
	var els = {
		modalDiv: "#modal-edit-spot",
		targetElement: ".add-edit-info"
	};
	var initialParams = {
		ph: 1
	}
	var formEls = {
		fieldsToSerialize: "#modal-edit-spot input:text, #modal-edit-spot input:radio",
		fieldsToValidate: "#modal-edit-spot input:text, #modal-edit-spot input:radio",
		requiredFields: "#modal-edit-spot input:text:not(.optional-field)"
	}
	var newModal = new BenefulMap.ModalEditSpot("Edit this Spot", "edit-spot", els, {}, BenefulMap.Constants.Snippets.MODAL_EDIT_SPOT, initialParams, formEls, ".spot-category input:radio", "#OtherCategorySuggestion", "account");
}


BenefulMap.fieldCountListener = function(textfield, countdown) {
	//N ext line checks for required textarea and counter objects or returns false
	if ($(textfield).length == 0 && $(countdown).length == 0) return false;
	var textfieldToBeCounted = $(textfield); // The textarea that will be counted and restricted
	var areaToShowCount = $(countdown);// The counter object. Visually shows the countdown of characters as it happens on the page
	var maxAmountOfCharacters = $(countdown).html(); // The maximum number of characters a user will be allowed. WARNING: Pulled directly from the markup of the counter object.
	textfieldToBeCounted.keyup(function(event) {
		if ($(this).val().length <= maxAmountOfCharacters) {
			areaToShowCount.html(maxAmountOfCharacters - $(this).val().length);
		}
		else if ($(this).val().length >= maxAmountOfCharacters) {
			$(this).val($(this).val().substring(0, maxAmountOfCharacters));
		}
	});
}

BenefulMap.userAccountTabs = function(tabs, sorter, defaultSort) {
	var selectTabFromAnchor = jQuery.url.attr("anchor");
	if(!selectTabFromAnchor) selectTabFromAnchor = 0;
	$(tabs).tabs({
		selected: selectTabFromAnchor,
		ajaxOptions: { data: {sort: defaultSort}, cache: false },
		load: function(event, ui) {
			$(sorter).change(function(event) {
				$(tabs).tabs("option", 'ajaxOptions', { data: {sort: $(this).val() }, cache: false });
				$(tabs).tabs("load", ui.index);		   
			});	   
		}
	});
	$(document).bind("tabs.reload", function(event) {
		$(tabs).load();
	});
}

// these functions are added from markup
function init(registrationContext, currentStep) {
    //Since it's a multistep registration process, handle Browser Back Button Clicks
    //If this was not here, and the user clicked back and tried to resubmit, they'd 
    //get a friendly error saying "You are already registered, please log in" message  

    var cookieCurrentStep = parseInt(get_cookie("step"));
    //alert(window.location.search.toString().indexOf("Page-Expired"));

    if (currentStep == 4) {
        //user is at the registration thankyou page.  clear the cookie
        clearStepCookie();
    }
    else if (cookieCurrentStep > currentStep) {
        var qstring = window.location;
        if (qstring.toString().indexOf("Page-Expired") == -1) {
            //user clicked back from some step ahead. take them to the custom PageExpired page
            window.location = "Page-Expired.aspx?step=" + cookieCurrentStep + "&reg=" + registrationContext;
        }
    }
    else {
        //set the cookie value to the current step
        window.onunload = function() { };
        document.cookie = "step=" + currentStep.toString() + ";path=/;host=localhost";
    }
}

//Get cookie routine by Shelley Powers 
function get_cookie(Name) {
    var search = Name + "="
    var returnvalue = "";
    if (document.cookie.length > 0) {
        offset = document.cookie.indexOf(search)
        // if cookie exists
        if (offset != -1) {
            offset += search.length
            // set index of beginning of value
            end = document.cookie.indexOf(";", offset);
            // set index of end of cookie value
            if (end == -1) end = document.cookie.length;
            returnvalue = unescape(document.cookie.substring(offset, end))
        }
    }
    return returnvalue;
}

function hideShowCatFoodFields(hideOrShow) {
    document.getElementById('catFoodOptional').style.display = hideOrShow;
}

function clearStepCookie() {
    var d = new Date();
    document.cookie = "step=;expires=Thu, 01-Jan-70 00:00:01 GMT" + "; path=/";
}

function enableOrDisableChkbx(txtBxId) {

    document.getElementById('dogname').innerHTML = document.getElementById(txtBxId).value;
    if (document.getElementById(txtBxId).value.length > 0 && document.getElementById('ctl00_MainContent_DoNotShowCheckBox').checked == false) {
        //document.getElementById('ctl00_MainContent_DoNotShowCheckBox').disabled = false;  
        document.getElementById('and').style.display = 'block';
        document.getElementById('dogname').style.display = 'block';
    }
    else {
        //document.getElementById('ctl00_MainContent_DoNotShowCheckBox').disabled = true; 
        document.getElementById('and').style.display = 'none';
    }
}



function embedFlash() {
	var swfContainer = "flashcontent";
	var swfPath = root + "_res/swf/TransformTool_account_page.swf";
	var expressInstallPath = root + "_res/swf/expressInstall.swf";

	var flashvars = {};
	flashvars.UserID = $("#flash-user-id").val();
	flashvars.PhotoID = $("#flash-photo-id").val();
    flashvars.endpointURI = $("#ctl00_MainContent_FlashEndPointUri").val();
    flashvars.serverLocation = $("#ctl00_MainContent_FlashServerLocation").val();
	flashvars.Context = "User";

	var params = {};
	params.quality = "high";
	params.allowScriptAccess = "sameDomain";
	params.wmode = "transparent";
	params.base = root + "_res/swf/";
	params.bgcolor = "#ffffff";

	var attributes = "";
	
	swfobject.embedSWF(swfPath, swfContainer, "570", "580", "10", expressInstallPath, flashvars, params, attributes);
}



/*this is a pop up window for 2 links on CreateAccount/Default.aspx page*/
function agreementpopup(url) {
    newwindow = window.open(url, 'name', 'scrollbars=1,height=500,width=500,resizable=0');
    if (window.focus) { newwindow.focus() }
    return false;
}



function OnTextFieldFocus_NextFieldToActivate(id, nextId, afterThatId) {
    if (document.getElementById(id).value.length > 0) {
        document.getElementById(nextId).disabled = false;
    }
    else {
        document.getElementById(nextId).selectedIndex = 0;
        document.getElementById(nextId).disabled = true;

        document.getElementById(afterThatId).selectedIndex = 0;
        document.getElementById(afterThatId).disabled = true;
    }
}

function OnDropDownFocus_NextFieldToActivate(id, nextId) {
    if (document.getElementById(id).selectedIndex > 0) {
        document.getElementById(nextId).disabled = false;
    }
    else {
        //document.getElementById(nextId).value = '';
        document.getElementById(nextId).disabled = true;
    }
}

function OnDropDownFocus_ActivateWetRdo(dogOrCat) {


    if (dogOrCat == 'cat') {

        if (document.getElementById('ctl00_MainContent_WetCatPreferences').selectedIndex > 1) {

            document.getElementById('ctl00_MainContent_CatWetHowOften_0').disabled = false;
            childElm = document.getElementById('ctl00_MainContent_CatWetHowOften_0');
            document.getElementById('ctl00_MainContent_CatWetHowOften_0').parentNode.disabled = false;

            document.getElementById('ctl00_MainContent_CatWetHowOften_1').disabled = false;
            childElm = document.getElementById('ctl00_MainContent_CatWetHowOften_1');
            document.getElementById('ctl00_MainContent_CatWetHowOften_1').parentNode.disabled = false;

            document.getElementById('ctl00_MainContent_CatWetHowOften_2').disabled = false;
            childElm = document.getElementById('ctl00_MainContent_CatWetHowOften_2');
            document.getElementById('ctl00_MainContent_CatWetHowOften_2').parentNode.disabled = false;

        }
        else {

            // document.getElementById('ctl00_MainContent_CatWetHowOften_0').disabled=true;
            document.getElementById('ctl00_MainContent_CatWetHowOften_0').checked = false;
            //document.getElementById('ctl00_MainContent_CatWetHowOften_1').disabled=true;
            document.getElementById('ctl00_MainContent_CatWetHowOften_1').checked = false;
            //document.getElementById('ctl00_MainContent_CatWetHowOften_2').disabled=true;
            document.getElementById('ctl00_MainContent_CatWetHowOften_2').checked = false;
        }

    }
    else {

        if (document.getElementById('ctl00_MainContent_WetDogPreferences').selectedIndex > 1) {
            document.getElementById('ctl00_MainContent_DogWetHowOften_0').disabled = false;
            childElm = document.getElementById('ctl00_MainContent_DogWetHowOften_0');
            document.getElementById('ctl00_MainContent_DogWetHowOften_0').parentNode.disabled = false;

            document.getElementById('ctl00_MainContent_DogWetHowOften_1').disabled = false;
            childElm = document.getElementById('ctl00_MainContent_DogWetHowOften_1');
            document.getElementById('ctl00_MainContent_DogWetHowOften_1').parentNode.disabled = false;

            document.getElementById('ctl00_MainContent_DogWetHowOften_2').disabled = false;
            childElm = document.getElementById('ctl00_MainContent_DogWetHowOften_2');
            document.getElementById('ctl00_MainContent_DogWetHowOften_2').parentNode.disabled = false;

        }
        else {
            //document.getElementById('ctl00_MainContent_DogWetHowOften_0').disabled=true;
            document.getElementById('ctl00_MainContent_DogWetHowOften_0').checked = false;
            //document.getElementById('ctl00_MainContent_DogWetHowOften_1').disabled=true;
            document.getElementById('ctl00_MainContent_DogWetHowOften_1').checked = false;
            //document.getElementById('ctl00_MainContent_DogWetHowOften_2').disabled=true;
            document.getElementById('ctl00_MainContent_DogWetHowOften_2').checked = false;
        }
    }
}

function enableOrDisableChkbx(txtBxId)
{
	document.getElementById('dogname').innerHTML = document.getElementById(txtBxId).value;	 
	if (document.getElementById(txtBxId).value.length > 0)
	{
		if (document.getElementById('ctl00_MainContent_DoNotShowCheckBox').checked == false )
		{
			//document.getElementById('ctl00_MainContent_DoNotShowCheckBox').disabled = false;  
			document.getElementById('and').style.display = 'block';	  
		}	  
	}
	else
	{
		//document.getElementById('ctl00_MainContent_DoNotShowCheckBox').disabled = true; 
		document.getElementById('and').style.display = 'none';		 
	}
}

function updateNickname(Nickname)
{
	if(Nickname.length > 0)
	{
		document.getElementById('Nickname').innerHTML = Nickname;
	}
	else
	{
		document.getElementById('Nickname').innerHTML = document.getElementById('ctl00_MainContent_HiddenFirstLastName').value;
	}
}


function checkChangedDoNotShow()
{
	if (document.getElementById('ctl00_MainContent_DoNotShowCheckBox').checked)
	{
		document.getElementById('dogname').style.display = 'none';
		document.getElementById('and').style.display = 'none';
	}
	else if (document.getElementById('ctl00_MainContent_Dog1NameTextBox').value.length > 0)  
	{
		document.getElementById('and').style.display = 'block';		
		document.getElementById('dogname').style.display = 'block';
	}
}



function populateNicknameOnLoad()//ctl00_MainContent_NicknameTextBox
{
	if (document.getElementById('ctl00_MainContent_NicknameTextBox').value.length > 0 && document.getElementById('ctl00_MainContent_NicknameTextBox').value != 'Enter Nickname')
	{
		document.getElementById('Nickname').innerHTML = document.getElementById('ctl00_MainContent_NicknameTextBox').value;
	}
	else
	{
		document.getElementById('Nickname').innerHTML = document.getElementById('ctl00_MainContent_HiddenFirstLastName').value;
	}
	if (document.getElementById('ctl00_MainContent_DoNotShowCheckBox').checked == false)
	{
		if (document.getElementById('ctl00_MainContent_Dog1NameTextBox').value.length > 0)
		{
			document.getElementById('dogname').innerHTML = document.getElementById('ctl00_MainContent_Dog1NameTextBox').value; 
			document.getElementById('and').style.display = 'block';
			document.getElementById('dogname').style.display = 'block';
		}
	}
	else
	{
			document.getElementById('and').style.display = 'none';
			document.getElementById('dogname').style.display = 'none';
	}
}

/*This is to force header links on /Account/Default.aspx to reload the page*/

BenefulMap.loggedInLinks = function ()
{
    $("#help-logout a").click(
        function () {
            window.location = ($(this).attr("href"));
            window.location.reload();
        }
    )
    return false;
}
