/*
 * Copyright (c) 2010, TopCoder, Inc. All rights reserved.
 */
$(document).ready(function () {

    /* jqTransform */
    $('.greenBar .barMidM dd, .registerForm, .contactForm, .reportForm').jqTransform({ imgPath: 'i/forms/' });
    /* select */
    $('.greenBar .barMidM dd select').ufd();
    $('.leftContent select').ufd({ skin: 'small' });

    /* Input Tips */
    $('.greenBar input.zipCode').input_tips("Your Zip Code");

    /* FAQs/Policy Expand and Collapse */
    $("#faq .questionBar, #policy .questionBar, #about .questionBar").live("click", function () {
        $(this).find("a.expandLink").removeClass("expandLink").addClass("collapseLink");
        $(this).removeClass("questionBar").addClass("questionExBar");
        $(this).parents(".qaPair").find(".answerSection").show();
    }).live("mouseenter", function () {
        $(this).addClass("hover");
    }).live("mouseleave", function () {
        $(this).removeClass("hover");
    });

    $("#faq .questionExBar, #policy .questionExBar, #about .questionExBar").live("click", function () {
        $(this).find("a.collapseLink").removeClass("collapseLink").addClass("expandLink");
        $(this).removeClass("questionExBar").addClass("questionBar");
        $(this).parents(".qaPair").find(".answerSection").hide();
    });

    $("#faq .flexAll .collapseLink").click(function () {
        $("#faq .questionExBar").trigger("click");
    });
    $("#faq .flexAll .expandLink").click(function () {
        $("#faq .questionBar").trigger("click");
    });
    $("#policy .flexAll .collapseLink").click(function () {
        $("#policy .questionExBar").trigger("click");
    });
    $("#policy .flexAll .expandLink").click(function () {
        $("#policy .questionBar").trigger("click");
    });
    $("#about .flexAll .collapseLink").click(function () {
        $("#about .questionExBar").trigger("click");
    });
    $("#about .flexAll .expandLink").click(function () {
        $("#about .questionBar").trigger("click");
    });


    /* Press Room Expand and Collapse */

    $("#pressRoom .questionBar").live("click", function () {
        $(this).find("a.expandLink").removeClass("expandLink").addClass("collapseLink");
        $(this).removeClass("questionBar").addClass("questionExBar");
        $(this).parents(".archives").find(".answerSection").show();
    }).live("mouseenter", function () {
        $(this).addClass("hover");
    }).live("mouseleave", function () {
        $(this).removeClass("hover");
    });

    $("#pressRoom .questionExBar").live("click", function () {
        $(this).find("a.collapseLink").removeClass("collapseLink").addClass("expandLink");
        $(this).removeClass("questionExBar").addClass("questionBar");
        $(this).parents(".archives").find(".answerSection").hide();
    });

    $("#pressRoom .flexAll .collapseLink").click(function () {
        $("#pressRoom .questionExBar").trigger("click");
    });
    $("#pressRoom .flexAll .expandLink").click(function () {
        $("#pressRoom .questionBar").trigger("click");
    });

    $('.reportForm .radioWrapper .jqTransformRadio, .registerForm .radioWrapper .jqTransformRadio').click(function () {
        var wrapper = $(this).parents('.radioWrapper');
        wrapper.removeClass('error');

        var labelWrapper = wrapper.find('.longLabel');
        if (labelWrapper.length <= 0) {
            labelWrapper = wrapper.find('.questionTxt');
        }
        if (labelWrapper.length > 0) {
            labelWrapper.find(".warning").remove();
        }

    });
    $('.reportForm .checkWrapper .jqTransformCheckbox').click(function () {
        var wrapper = $(this).parents('.checkWrapper');
        wrapper.removeClass('error');

        var labelWrapper = wrapper.find('.longLabel');
        if (labelWrapper.length <= 0) {
            labelWrapper = wrapper.find('.questionTxt');
        }
        if (labelWrapper.length > 0) {
            labelWrapper.find(".warning").remove();
        }
    });
    $(".reportForm input[type='text']").focus(function () {
        var parent = $(this).parents(".reportFormRow");
        var length = $(this).attr('maxlength') + 0;
        if (length > 1000 || length <= 0) {
            length = 0;
        }
        parent.removeClass("error");
        parent.find(".warning").remove();
        parent.find(".format").show();
    });
    $(".reportForm textarea").focus(function () {
        var parent = $(this).parents(".textAreaWrapper");
        parent.removeClass("error");
        parent.find(".warning").remove();
        parent.find(".format").show();
    });
    /* Report submit */
    $(".reportForm a.button").click(function () {
        var hasError = false;
        $('textArea').each(function (idx, element) {
            var wrapper = $(this).parents('.textAreaWrapper');
            if ($.trim($(this).val()) == "" || $.trim($(this).val()).length > 250) {
                hasError = true;
                wrapper.addClass("error");
                wrapper.find(".warning").remove();
                var str = "This field is required";
                if ($.trim($(this).val()).length > 250) {
                    str = "Words limit exceed";
                }
                $("<span />", {
                    "class": "warning",
                    "text": str
                }).appendTo(wrapper);
                wrapper.find(".format").hide();
                if (wrapper.find('.limitLabel').length > 0) {
                    wrapper.find(".limitLabel").remove();
                    $('<div class="limitLabel gray">(Limit 250 words).</div>').appendTo(wrapper);
                }
            }

        });
        $('.checkWrapper').each(function (idx, element) {
            var wrapper = $(element);
            if (wrapper.find('.jqTransformChecked').length > 0) {
            } else {
                wrapper.addClass('error');
                hasError = true;
                var labelWrapper = wrapper.find('.longLabel');
                if (labelWrapper.length <= 0) {
                    labelWrapper = wrapper.find('.questionTxt');
                }
                labelWrapper.find(".warning").remove();
                $("<span />", {
                    "class": "warning",
                    "text": "This field is required",
                    "style": "float: none; font-weight: normal;line-height: 18px;"
                }).appendTo(labelWrapper);
            }
        });
        $('.radioWrapper').each(function (idx, element) {
            var wrapper = $(element);
            if (wrapper.find('.jqTransformChecked').length > 0) {
            } else {
                wrapper.addClass('error');
                hasError = true;

                var labelWrapper = wrapper.find('.longLabel');
                if (labelWrapper.length <= 0) {
                    labelWrapper = wrapper.find('.questionTxt');
                }
                labelWrapper.find(".warning").remove();
                $("<span />", {
                    "class": "warning",
                    "text": "This field is required",
                    "style": "float: none; font-weight: normal;line-height: 18px;"
                }).appendTo(labelWrapper);
            }
        });
        $(".reportForm input[type='text']").each(function () {
            var parent = $(this).parents(".reportFormRow");
            var content = $.trim($(this).val());
            var length = $(this).attr('maxlength') + 0;
            if (length > 1000 || length <= 0) {
                length = 0;
            }
            if ($.trim($(this).val()) == "" || content.length < length) {
                if (!$(this).hasClass('optional')) {
                    hasError = true;
                    $(this).val(content);
                    parent.addClass("error");
                    parent.find(".warning").remove();
                    $("<span />", {
                        "class": "warning",
                        "text": "This field is required"
                    }).appendTo(parent);
                    parent.find(".format").hide();
                    if (parent.find('.clear').length > 0) {
                        parent.find(".clear").remove();
                        $('<div class="clear" />').appendTo(parent);
                    }
                }
            } else if ((($(this).hasClass('phone1') && !/^\d{3}$/.test($(this).val()))) ||
                    (($(this).hasClass('phone2') && !/^\d{3}$/.test($(this).val()))) ||
                    (($(this).hasClass('phone3') && !/^\d{4}$/.test($(this).val())))) {
                hasError = true;
                parent.addClass("error");
                parent.find(".warning").remove();
                $("<span />", {
                    "class": "warning",
                    "text": "Invalid phone."
                }).appendTo(parent);
                parent.find(".format").hide();
                if (parent.find('.clear').length > 0) {
                    parent.find(".clear").remove();
                    $('<div class="clear" />').appendTo(parent);
                }
            } else if ($(this).hasClass('zipCode') && !/^\d{5}$/.test($(this).val())) {
                hasError = true;
                parent.addClass("error");
                parent.find(".warning").remove();
                $("<span />", {
                    "class": "warning",
                    "text": "Invalid zip."
                }).appendTo(parent);
                parent.find(".format").hide();
                if (parent.find('.clear').length > 0) {
                    parent.find(".clear").remove();
                    $('<div class="clear" />').appendTo(parent);
                }
            } else if (($(this).hasClass('email') && !/^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/.test($(this).val()))) {
                hasError = true;
                parent.addClass("error");
                parent.find(".warning").remove();
                $("<span />", {
                    "class": "warning",
                    "text": "Invalid email."
                }).appendTo(parent);
                parent.find(".format").hide();
                if (parent.find('.clear').length > 0) {
                    parent.find(".clear").remove();
                    $('<div class="clear" />').appendTo(parent);
                }
            }
        });
        if (hasError) {
            $(window).scrollTop($('.error:first').position().top);
            return false;
        };
        $('#mainForm').submit();
        return true;
    });


    /* Register submit */
    $(".registerForm a.button").click(function () {
        var hasError = false;
        $(".registerForm input[type='text']").each(function () {
            var parent = $(this).parents("li");
            if ($.trim($(this).val()) == "") {
                if (!$(this).hasClass('optional')) {
                    hasError = true;
                    $(this).val("");
                    parent.addClass("error");
                    parent.find(".warning").remove();
                    $("<span />", {
                        "class": "warning",
                        "text": "This field is required"
                    }).appendTo(parent);
                    parent.find(".format").hide();
                }
            } else if ((($(this).hasClass('phone1') && !/^\d{3}$/.test($(this).val()))) ||
                    (($(this).hasClass('phone2') && !/^\d{3}$/.test($(this).val()))) ||
                    (($(this).hasClass('phone3') && !/^\d{4}$/.test($(this).val())))) {
                hasError = true;
                parent.addClass("error");
                parent.find(".warning").remove();
                $("<span />", {
                    "class": "warning",
                    "text": "Invalid phone."
                }).appendTo(parent);
                parent.find(".format").hide();
            } else if ($(this).hasClass('zipCode') && !/^\d{5}$/.test($(this).val())) {
                hasError = true;
                parent.addClass("error");
                parent.find(".warning").remove();
                $("<span />", {
                    "class": "warning",
                    "text": "Invalid zip code format."
                }).appendTo(parent);
                parent.find(".format").hide();
            } else if (($(this).hasClass('email') && !/^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/.test($(this).val()))) {
                hasError = true;
                parent.addClass("error");
                parent.find(".warning").remove();
                $("<span />", {
                    "class": "warning",
                    "text": "Invalid email format."
                }).appendTo(parent);
                parent.find(".format").hide();
            }
        });
        $(".registerForm select").each(function () {
            if ($('option:selected', $(this)).index() == 0) {
                var parent = $(this).parents(".row");
                hasError = true;
                parent.addClass("error");
                parent.find(".warning").remove();
                $("<span />", {
                    "class": "warning",
                    "text": "This field is required"
                }).appendTo(parent);
                parent.find(".format").hide();
            }
        });
        $('.radioWrapper').each(function (idx, element) {
            var wrapper = $(element);
            if (wrapper.find('.jqTransformChecked').length > 0) {
            } else {
                wrapper.addClass('error');
                hasError = true;
            }
        });
        //         if($('.agreeBox .jqTransformChecked').length == 0){
        //             $('.agree').addClass("error");
        //			 hasError = true;
        //         }else{
        //         		$('.agree').removeClass("error");
        //         }
        if (hasError) {
            $(window).scrollTop($('.error:first').position().top);
            return false;
        };
        $('#mainForm').submit();
        return true;
    });

    //	 $('.agreeBox .jqTransformCheckbox').click(function() {
    //		 var parent = $(this).parents('.agree');
    //		 parent.removeClass('error');
    //	 });
    $(".registerForm input[type='text']").focus(function () {
        var parent = $(this).parents("li");
        parent.removeClass("error");
        parent.find(".warning").remove();
        parent.find(".format").show();
    });
    $(".registerForm select").change(function () {
        var parent = $(this).parents(".row");
        if ($('option:selected', $(this)).index() != 0) {
            parent.removeClass("error");
            parent.find(".warning").remove();
            parent.find(".format").show();
        }
    });

    /* contactForm submit */
    $(".contactForm a.button").click(function () {
        var hasError = false;

        $(".contactForm input[type='text']").each(function () {
            var parent = $(this).parents(".row");
            if ($.trim($(this).val()) == "") {
                if (!$(this).hasClass('optional')) {
                    hasError = true;
                    $(this).val("");
                    parent.addClass("error");
                    parent.find(".warning").remove();
                    parent.find(".clear").before($("<span />", {
                        "class": "warning",
                        "text": "This field is required"
                    }));
                    parent.find(".format").hide();
                }
            } else if ((($(this).hasClass('phone1') && !/^\d{3}$/.test($(this).val()))) ||
                    (($(this).hasClass('phone2') && !/^\d{3}$/.test($(this).val()))) ||
                    (($(this).hasClass('phone3') && !/^\d{4}$/.test($(this).val())))) {
                hasError = true;
                parent.addClass("error");
                parent.find(".warning").remove();
                parent.find(".clear").before($("<span />", {
                    "class": "warning",
                    "text": "Invalid phone."
                }));
                parent.find(".format").hide();
            } else if ($(this).hasClass('zipCode') && !/^\d{5}$/.test($(this).val())) {
                hasError = true;
                parent.addClass("error");
                parent.find(".warning").remove();
                parent.find(".clear").before($("<span />", {
                    "class": "warning",
                    "text": "Invalid zip code."
                }));
                parent.find(".format").hide();
            } else if (($(this).hasClass('email') && !/^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/.test($(this).val()))) {
                hasError = true;
                parent.addClass("error");
                parent.find(".warning").remove();
                parent.find(".clear").before($("<span />", {
                    "class": "warning",
                    "text": "Invalid email."
                }));
                parent.find(".format").hide();
            }
        });

        $(".contactForm select").each(function () {
            if ($('option:selected', $(this)).index() == 0) {
                var parent = $(this).parents(".row");
                hasError = true;
                parent.addClass("error");
                parent.find(".warning").remove();
                parent.find(".clear").before($("<span />", {
                    "class": "warning",
                    "text": "This field is required"
                }));
            }
        });

        if (hasError) {
            if ($('#findProsFormFrame', top.document).length > 0) {
                $(window.parent).scrollTop($('.error:first').position().top + $('#findProsFormFrame', top.document).position().top);
            } else {
                $(window).scrollTop($('.error:first').position().top);
            }
            return false;
        };

        $('#mainForm').submit();
        return true;
    });
    $(".contactForm input[type='text']").focus(function () {
        var parent = $(this).parents(".row");
        parent.removeClass("error");
        parent.find(".warning").remove();
        parent.find(".format").show();
    });
    $(".contactForm select").change(function () {
        var parent = $(this).parents(".row");
        if ($('option:selected', $(this)).index() != 0) {
            parent.removeClass("error");
            parent.find(".warning").remove();
            parent.find(".format").show();
        }
    });

    /* More detail show/hide for search results */
    $(".resultList .detailLink").click(function () {
        $(this).blur();
        var moreDetail = $(this).parents("li").find(".moreDetail");
        if (moreDetail.is(":hidden")) {
            $(this).text("Hide More Detail..");
            moreDetail.show();
        } else {
            $(this).text("More Detail..");
            moreDetail.hide();
        }
        return false;
    });

    /* Zip Code show/hide */
    $(".zipCodeServedLink").click(function () {
        $(this).blur();
        var zipcode = $(".zipcodeServed");
        if (zipcode.is(":hidden")) {
            $(this).find(".show").text("HIDE");
            zipcode.show();
        } else {
            $(this).find(".show").text("SHOW");
            zipcode.hide();
        }
    });

    function getParameter() {
        var urls = location.search.match(/[\?\&]mode=([^\&]*)(\&?)/i);
        if (urls && urls.length && urls.length > 1) {
            return urls[1];
        }
        return urls;
    }

    if ($('#policy').length > 0) {
        if (getParameter() == 'policy') {
            $('.qaPair:first dl').removeClass('questionExBar').addClass('questionBar');
            $('.qaPair:first a.collapseLink').removeClass('collapseLink').addClass('expandLink');
            $('.qaPair:first .answerSection').addClass('hide');
            $('.qaPair:last dl').removeClass('questionBar').addClass('questionExBar');
            $('.qaPair:last a.expandLink').removeClass('expandLink').addClass('collapseLink');
            $('.qaPair:last .answerSection').removeClass('hide');
        }
    }

    if ($('#article').length > 0) {
        var urls = location.search.match(/[\?\&]title=(.*)/i);
        if (urls != null) {
            $('.greyBar h1').text(decodeURIComponent(urls[1]));
        }
    }

    $('.searchBtn').click(function () {
        var zipCode = $('.findProZipCode').val();
        if ((zipCode.length == 0) || (zipCode == 'Your Zip Code')) {
            alert('Please enter a zip code.');
        }
        else {
            var zipCodePattern = /^\d{5}$/;
            if (!zipCodePattern.test(zipCode)) {
                alert('Please enter a valid zip code.');
            }
            else {
                var categoryId = $('.findProServiceSelect').val();
                if (categoryId == '0') {
                    alert('Please select a service.');
                }
                else {
                    var categoryName = $('.findProServiceSelect option:selected').text();
                    var href = $(this).attr('href');
                    setZipCodeCookie(zipCode);
                    location.href = href + '?zipCode=' + zipCode + '&categoryId=' + categoryId +
                        '&categoryName=' + encodeURIComponent(categoryName);
                }
            }
        }
        return false;
    });

    $('body').click(function () {
        $('.opt').remove();
    });

    setAutoTab(3, 'leftContent_phone1', 'leftContent_phone2');
    setAutoTab(3, 'leftContent_phone2', 'leftContent_phone3');

    setAutoTab(3, 'leftContent_altPhone1', 'leftContent_altPhone2');
    setAutoTab(3, 'leftContent_altPhone2', 'leftContent_altPhone3');

});

 /* define input tip function */
(function($){
    $.fn.input_tips = function(tipValue){
        this.each(function(){
            $(this).data("tipValue", tipValue);
            function focus(el){
                if($(el).val() == tipValue){
                    $(el).val("");
                    $(el).removeClass("inputTips");
                }
                return;
            }

            function blur(el){
               if($(el).val() == "" || $(el).val() == tipValue){
                    $(el).val(tipValue);
                    $(el).addClass("inputTips");
                }
                return;
            }

            blur(this);
            $(this).focus(function(){
                focus(this);
            }).blur(function(){
                blur(this);
            })
       })
    };
 })(jQuery);

function setZipCodeCookie(value) {
    document.cookie = "zipCode=" + value + ";path=/";
}

function setAutoTab(numCharacters, currentId, nextId) {
    var currentTextBox = $('#' + currentId);
    var nextTextBox = $('#' + nextId);

    currentTextBox.live('keyup', function (e) {
        var keyID = (window.event) ? event.keyCode : e.keyCode;

        if ((currentTextBox.val().length >= numCharacters) &&
            ((keyID >= 48 && keyID <= 90) || (keyID >= 96 && keyID <= 105))) {
            nextTextBox.focus();
        }
    });
}
