var JBFX = JBFX || {};

JBFX.home = {
    pgpList: null,
    selectedProfHiddenFieldId: null,
    zipCodeControlId: null,
    auditPageTrackingHandlerURL: null,
    auditTrackingCookieInfo: null,
    zipCodeValidationHandlerURL: null,
    init: function (profHandlerURL, auditHandlerURL, zipValHandlerURL, selectedProfHDId, txtZipCodeId, cookieInfohdId) {

        //		NOTE: we do not have any placeholds in homepage		
        //		if ( !( $.browser.msie && $.browser.version < 7 ) ) {
        //			$( "input[placeholder], textarea[placeholder]" ).placehold();
        //		}	

        var $select = $("select#profession"),
			$button = $("input#panelOnePGSelect"),
			$browseProfLink = $("a#browse-profession-groups");

        auditPageTrackingHandlerURL = auditHandlerURL;
        zipCodeValidationHandlerURL = zipValHandlerURL;
        zipCodeControlId = txtZipCodeId;
        selectedProfHiddenFieldId = selectedProfHDId;
        auditTrackingCookieInfo = jQuery.parseJSON($('#' + cookieInfohdId).val());
        //init first ddl to new styles.		
        //$select.sb({ animDuration: 0, fixedWidth: true });

        $button.bind("click", function (e) {
            e.preventDefault();
            //show loading message			
        });

        if (navigator.cookieEnabled) {
            JBFX.home.initProfessionsData(profHandlerURL, $select, $button, $browseProfLink);
        }
        else {
            JBFX.home.disablePanelOneActuators(2, $button, $browseProfLink);
        }
    },
    initProfessionsData: function (handlerURL, profSelect, goButton, browseAllLink) {

        $.ajax({
            dataType: "json",
            timeout: 8000,
            success: function (rsp, success, xhr) {
                if (xhr.status == 200) {
                    pgpList = rsp;
                    JBFX.home.initPanelOneActuators(profSelect, goButton, browseAllLink);
                }
                else {
                    JBFX.home.disablePanelOneActuators(1, goButton, browseAllLink);
                }
            },
            error: function (er) {
                JBFX.home.disablePanelOneActuators(1, goButton, browseAllLink);
            },
            url: handlerURL + '?pDesc=true&pgDesc=true&F=Json'
        });
    },
    initPanelOneActuators: function (profSelector, goButton, browseAllLink) {
        profSelector.bind("change", function () {
            JBFX.home.validateStepOne(profSelector);
        });

        goButton.unbind('click');
        goButton.bind("click", function (e) {
            e.preventDefault();
            JBFX.home.validateStepOne(profSelector);
        });
        browseAllLink.bind("click", function (e) {
            JBFX.home.handleAuditTrackingCookie();
            var $auditQuery = '?va=13&ct=1';
            JBFX.home.auditPageTracking($auditQuery);
            JBFX.home.slideProfessionGroups();
        });
        //adding signup link on the top
        $SignUpLink = $("a#lnkHomePageSignUp");
        $SignUpLink.bind("click", function (e) {
            JBFX.home.handleAuditTrackingCookie();
            var $auditQuery = '?va=13&ct=1';
            JBFX.home.auditPageTracking($auditQuery);
            JBFX.home.slideProfessionGroups();
        });
    },
    handleAuditTrackingCookie: function () {

        var auditTrackingCookie = $.cookie("a_pt_id");
        if (auditTrackingCookie == null || auditTrackingCookie == undefined) {
            $.cookie("a_pt_id", auditTrackingCookieInfo.Value, { domain: auditTrackingCookieInfo.Domain, path: '/', expires: auditTrackingCookieInfo.Expires });
            try {
                if (auditTrackingCookieInfo == null || auditTrackingCookieInfo == undefined) {
                    throw "a_pt_id cookie is not created. AuditTrackingCookieInfo JSON either null or undefined";
                }
                var checkAuditTrackingCookie = $.cookie("a_pt_id");
                if (checkAuditTrackingCookie == null || checkAuditTrackingCookie == undefined) {
                    throw "a_pt_id cookie is not created. Cookie iss either null or undefined";
                }
                else {
                    if (checkAuditTrackingCookie != auditTrackingCookieInfo.Value) {
                        throw "a_pt_id cookie value hasnt set correctly when creating. CorrectValue[" + auditTrackingCookieInfo.Value + "], ErrorValue[" + checkAuditTrackingCookie + "]";
                    }
                }
            }
            catch (err) {
                doError(err);
            }
        }
    },
    disablePanelOneActuators: function (errorCode, goButton, browseAllLink) {
        goButton.bind("click", function (e) {
            e.preventDefault();
            if (errorCode == 1)
                $("div#divNoResponseError").fadeIn(500);
            else if (errorCode == 2)
                $("div#divCookiesDisabledError").fadeIn(500);
        });
        browseAllLink.bind("click", function (e) {
            e.preventDefault();
            if (errorCode == 1)
                $("div#divNoResponseError").fadeIn(500);
            else if (errorCode == 2)
                $("div#divCookiesDisabledError").fadeIn(500);
        });
        $SignUpLink = $("a#lnkHomePageSignUp");
        $SignUpLink.bind("click", function (e) {
            e.preventDefault();
            if (errorCode == 1)
                $("div#divNoResponseError").fadeIn(500);
            else if (errorCode == 2)
                $("div#divCookiesDisabledError").fadeIn(500);
        });
    },
    initLabelHovers: function (labels) {
        var t;

        labels.each(function () {
            var $label = $(this),
				$span = $label.siblings("span.info"),
				$li = $label.parents("li:first"),
				$ul = $li.parents("ul:first");

            $label.hover(
				function () {
				    t = setTimeout(function () {
				        $span.css({
				            top: $li.position().top + parseFloat($li.css("margin-top")) + 30,
				            left: $li.position().left
				        }).fadeIn(500);
				    }, 1000);
				},
				function () {
				    clearTimeout(t);
				    $span.fadeOut(400);
				}
			);
        });
    },

    initRadioButtons: function (radios, labels) {
        radios.bind("click", function () {
            var $this = $(this),
				$label = $this.parent(),
				$errorProf = $("div#panel-two div#divProfessionError");

            $errorProf.fadeOut(500);

            labels.removeClass("checked");
            $label.addClass("checked");

            //set the professionhidden field
            var pId = $this.attr("pId");
            $('#' + selectedProfHiddenFieldId).val(pId);

            //            if (!$("input#" + zipCodeControlId).val()) {
            //                $("img#zip-hint").fadeIn(500, function() {
            //                    $("input#" + zipCodeControlId).focus();
            //                });
            //            }
        });
    },
    initProfessionGroupRadioButtons: function (radios, labels, selectPGButton) {
        radios.bind("click", function () {
            var $this = $(this),
				$label = $this.parent();

            labels.removeClass("checked");
            $label.addClass("checked");
        });
        selectPGButton.bind("click", function () {

            var $innerContainer = $("div#panel-profession-group");
            var $checkedPGInput = $("input:checked", $innerContainer);
            if ($checkedPGInput.length == 1) {
                var pgId = $checkedPGInput.attr("pgId");
                var $auditQuery = '?va=12&ct=1&pgId=' + pgId;
                JBFX.home.auditPageTracking($auditQuery);
                JBFX.home.slideProfessions(pgId, 2);
            }
            else {
                alert('Please select a profession.');
            }
        });
    },

    initProfessionsPanel: function (pgId) {
        var $rsp = $("div#choose-field-form"),
			$radios = $(":radio", $rsp),
			$labels = $("div#profession-field-container label", $rsp);

        JBFX.home.initRadioButtons($radios, $labels);
        JBFX.home.initLabelHovers($labels);
    },

    slideProfessions: function (pgId, step) {
        //selection already validated at this point.
        var $container = $("div#panel-container"),
			$changeProfession = $("select#change-profession"),
			$input = $("input#" + zipCodeControlId),
			$button = $("div#choose-field-form button.imageSubmit"),
			$changeProfession = $("select#change-profession");

        JBFX.home.populateProfessionFields(pgId);
        var slideWidth = "-960px";
        if (step == 2) {
            slideWidth = "-1920px";
        }

        $container.animate({
            "margin-left": slideWidth
        }, 500);

        //set the step2 pg selected pg
        $changeProfession.val(pgId)
        //initialize the second ddl to new styles		
        $changeProfession.sb({ animDuration: 0, fixedWidth: true });

        $changeProfession.bind("change", function () {
            JBFX.home.rePopulateProfessions(this);
        });

        $button.bind("click", function (e) {
            e.preventDefault();
            JBFX.home.validateStepTwo($input);

        });

        JBFX.home.initProfessionsPanel(pgId);
    },
    slideProfessionGroups: function () {

        var $container = $("div#panel-container"),
			$innerContainer = $("div#panel-profession-group");

        JBFX.home.populateProfessionGroupFields();

        var $radios = $(":radio", $innerContainer),
			$labels = $("label", $innerContainer),
            $selectPGButton = $("a", $innerContainer);

        JBFX.home.initProfessionGroupRadioButtons($radios, $labels, $selectPGButton);
        JBFX.home.initLabelHovers($labels);

        $innerContainer.show();
        $container.animate({
            "margin-left": "-960px"
        }, 500);
    },
    rePopulateProfessions: function (select) {
        var $select = $(select),
			$errorProf = $("div#panel-two div#divProfessionError");

        $errorProf.fadeOut(500);
        $('#' + selectedProfHiddenFieldId).val('');

        var $auditQuery = '?va=14&ct=1&pgId=' + $select.val();
        JBFX.home.auditPageTracking($auditQuery);

        JBFX.home.populateProfessionFields($select.val());
        JBFX.home.initProfessionsPanel($select.val());
    },
    populateProfessionFields: function (professionGroupId) {

        var $container = $("div#profession-field-container"),
			$selPG,
			$profDescContainer = $("p#pProfessionGroupDesc");
        //$profCalloutImage = $("img#imgProfCallout");

        $.each(pgpList, function (pg) {
            if (pgpList[pg].id == professionGroupId) {
                $selPG = pgpList[pg];
                return false;
            }
        });

        //set pg desc and callout image
        JBFX.home.populateProfessionGroupHeader($selPG, 'CustomerSupport');


        var profTempl = $("#professionFieldsTemplate").tmpl($selPG);
        $container.empty();
        $container.append(profTempl);
    },
    populateProfessionGroupHeader: function (selPG, imgName) {
        var $profDescContainer = $("p#pProfessionGroupDesc"),
        //$profCalloutImage = $("img#imgProfCallout"),
			$headerContailer = $("div#panel-two div.header");

        $headerContailer.css("background-image", "url(images/professiongroups/ico" + selPG.id + ".png)");
        $profDescContainer.text(selPG.professionGroupDesc);
        //$profCalloutImage.attr('src', 'images/professiongroups/callout' + selPG.id + '.gif');
        //$profCalloutImage.attr('alt', selPG.name);
    },
    populateProfessionGroupFields: function () {

        var $container = $("div#profession-group-field-container ul");
        var profTempl = $("#professionGroupsTemplate").tmpl(pgpList);

        $container.empty();
        $container.append(profTempl);

    },
    auditPageTracking: function (query) {

        $.ajax({
            dataType: "json",
            url: auditPageTrackingHandlerURL + query
        });
    },
    validateStepOne: function (select) {
        var $select = $(select),
			$error = $("div#panel-one div#divSelectPGError");

        if ($select.val()) {
            $error.fadeOut(500);
            JBFX.home.handleAuditTrackingCookie();
            var $auditQuery = '?va=12&ct=1&pgId=' + $select.val();
            JBFX.home.auditPageTracking($auditQuery);

            JBFX.home.slideProfessions($select.val(), 1);
        } else {
            $error.fadeIn(500);
        }
    },
    validateStepTwo: function (input) {
        var $input = $(input),
			$errorProf = $("div#panel-two div#divProfessionError"),
			$errorZip = $("div#panel-two div#divZipError"),
			$profHiddenFiled = $('#' + selectedProfHiddenFieldId);

        if (!$profHiddenFiled.val()) {
            $errorProf.fadeIn(500);
            $errorZip.fadeOut(500);
        }
        else if (!$input.val()) {
            $errorProf.fadeOut(500);
            $errorZip.html('Please enter your zip code to continue');
            $errorZip.fadeIn(500);
            $input.focus();

        }
        else {
            //do zipcode validation.
            var zipQuery = '?vll=true&zCd=' + $input.val();
            var isValidZip = false;
            $.ajax({
                dataType: "json",
                async: false,
                url: zipCodeValidationHandlerURL + zipQuery,
                success: function (data) {
                    if (data && data.ErrorCode == 0) {
                        isValidZip = true;
                    }
                }
            });
            if (!isValidZip) {
                $errorProf.fadeOut(500);
                $errorZip.html('Invalid Zip Code');
                $errorZip.fadeIn(500);
                $input.focus();
                return;
            }

            $errorProf.fadeOut(500);
            $errorZip.fadeOut(500);
            //audit
            var $auditQuery = '?va=8&ct=1&pId=' + $profHiddenFiled.val() + '&pc=' + $input.val();
            JBFX.home.auditPageTracking($auditQuery);

            // Process form			
            var $form = $("form");
            $form.submit();
        }
    }
};


