var _hostname = window.location.hostname;
if (_hostname.search("hopublic") != -1) {
    WORKING_SERVER_PATH = "/polycarb/";
    WORKING_SERVER_DOMAIN = "http://hopubliccontent1stage.rohmhaas.com";
} else {
    WORKING_SERVER_PATH = "/";
    WORKING_SERVER_DOMAIN = "";
}

function isIE() {
    return (navigator.appName == 'Microsoft Internet Explorer') ? true : false;
}

//search keyword redirect-------------------------------------
//Since the live and preview servers' root folders differ (Preview:"/polycarb/" Live:"/"), the search redirect will not work on the preview server

function keyword(){
	var sKeyword = $('[name=q]').val();
	sKeyword = sKeyword.toLowerCase();
	if 	(sKeyword == 'about'){
		redirect('/about/');
		return false;
	}
	else if (sKeyword == 'adhesive & grouts'){
		redirect('/applications/adhesives/');
		return false;
	}
	else if(sKeyword == 'applications'){
		redirect('/applications/');
		return false;
	}
	else if(sKeyword == 'asset preservation'){
		redirect('/asset_preservation/');
		return false;
	}
	else if(sKeyword == 'bridge decks'){
		redirect('/applications/bridge_decks/');
		return false;
	}
	else if(sKeyword == 'bridge deck infrastructure'){
		redirect('/asset_preservation/bridge_decks/');
		return false;
	}
	else if(sKeyword == 'chemical emergency response'){
		redirect('/hazard.asp');
		return false;
	}
	else if(sKeyword == 'contact'){
		redirect('/contact/');
		return false;
	}
	else if(sKeyword == 'events'){
		redirect('/news/events/');
		return false;
	}
	else if(sKeyword == 'find a representative'){
		redirect('/findarep/');
		return false;
	}
	else if(sKeyword == 'frequently asked questions'){
		redirect('/asset_preservation/faq.asp');
		return false;
	}
	else if(sKeyword == 'msds'){
		redirect('/technical_information/msds/');
		return false;
	}
	else if(sKeyword == 'news & events'){
		redirect('/news/');
		return false;
	}
	else if(sKeyword == 'newsletters'){
		redirect('/newsletters/');
		return false;
	}
	else if(sKeyword == 'parking'){
		redirect('/applications/parking/');
		return false;
	}
	else if(sKeyword == 'parking deck infrastructure'){
		redirect('/asset_preservation/parking/');
		return false;
	}
	else if(sKeyword == 'pavement markings'){
		redirect('/applications/pavement_markings/');
		return false;
	}
	else if(sKeyword == 'pavement safety markings'){
		redirect('/asset_preservation/pavement_safety_markings/');
		return false;
	}
	else if(sKeyword == 'press releases'){
		redirect('/news/press/');
		return false;
	}
	else if(sKeyword == 'products'){
		redirect('/products/');
		return false;
	}
	else if(sKeyword == 'request access'){
		redirect('/request_access/');
		return false;
	}
	else if(sKeyword == 'sealers & coatings'){
		redirect('/applications/sealers/');
		return false;
	}
	else if(sKeyword == 'technical data sheet'){
		redirect('/technical_information/msds/');
		return false;
	}
	else if(sKeyword == 'technical information'){
		redirect('/technical_information/');
		return false;
	}
	else if(sKeyword == 'tds'){
		redirect('/technical_information/msds/');
		return false;
	}
	else if(sKeyword == 'training'){
		redirect('/technical_information/training/');
		return false;
	}
	else{
		return true;
	}
}

function redirect(sUrl){
	window.location = sUrl;
}

//------------------------------------------------------------

$(document).ready(function () {

    //search click and blur handler
    $('.search-box input').click(function () {
        if ($(this).val() == 'Search') {
            $(this).val('');
        }
    });
    $('.search-box input').blur(function () {
        if ($(this).val() == '') {
            $(this).val('Search');
        }
    });
    //-----------------------------


    $("body").append('<div id="overlay_message" class="overlay"><div class="wrap"></div></div>');

    $(".scrollable").scrollable({ circular: true }).autoscroll({ autoplay: true, interval: 10000, autopause: true }).navigator();

    //$(".homeflash").mouseover(function () { $(".browse").css({ opacity: 1, display: "block" }); });
    //$(".homeflash").mouseout(function () { $(".browse").css({ opacity: 1, display: "none" }); });

    /*if (!isIE()) {
    $(".browse").delay(500).fadeOut("fast");
    } else {
    $(".browse").delay(500).hide();
    }*/

    $(".btn-download").click(function (e) {
        e.stopPropagation();
        var position = $(this).offset();
        $(".btn-download").not(this).css({ zIndex: 800 })
        $(this).css({ zIndex: 999 })

        $("#downloads_menu").show().css({ left: (position.left - $("#downloads_menu").width() + 10 + $(".btn-download").width()) + "px", top: (position.top - 10) + "px" })
        if ($(this).find("ul:first").length) {
            $("#downloads_menu .content").html($(this).html())
            createDownloadLinkEvents();
        } else {
            $("#downloads_menu .content").html("<p>No downloads available</p>")
        }
    });

    $("#downloads_menu").click(function (e) {
        e.stopPropagation();
    });

    // Close menus on document click
    $(document).click(function (e) {
        $("#downloads_menu").hide();
        $(".btn-download").css({ zIndex: 999 })
    });

    selectedFile = '';

    if (typeof loggedInUser != 'undefined' && loggedInUser.load.length > 1) {
        window.open(loggedInUser.load, "_blank");
    }

    function signIn() {
        $.ajax({
            type: "POST",
            url: WORKING_SERVER_PATH + "ajax/signin.asp",
            data: "login=1&e=" + $('#signin_email').val() + "&p=" + $('#signin_password').val() + "&f=" + $(".signin_file_to_load").val(),
            success: function (response) {
                eval(response);
                if (response.status == 'success') {

                    _gaq.push(['_setCustomVar',
                        1,                   // This custom var is set to slot #1.  Required parameter.
                        'User-ID',     // The name acts as a kind of category for the user activity.  Required parameter.
                        response.user.id,               // This value of the custom variable.  Required parameter.
                        1                    // Sets the scope to session-level.  Optional parameter.
                    ]);

                    _gaq.push(['_setCustomVar',
                        2,                   // This custom var is set to slot #1.  Required parameter.
                        'User-Name',     // The name acts as a kind of category for the user activity.  Required parameter.
                        response.user.firstname + " " + response.user.lastname,               // This value of the custom variable.  Required parameter.
                        1                    // Sets the scope to session-level.  Optional parameter.
                    ]);

                    _gaq.push(['_trackEvent', 'Authentication', 'Success', response.user.firstname + " " + response.user.lastname]);

                    window.location.reload(true);
                } else {
                    if (signinAttempts > 0) {
                        errorMessage = 'Still wrong. Try <a href="javascript://" class="error_link_recover">recovering your password</a>.';
                        $('.overlay .error ').html(errorMessage);
                        $('.error_link_recover').click(function () {
                            changeTab('.recoverpassword');
                        });
                    } else {
                        errorMessage = 'Wrong username or password. Please try again.';
                        var div = $('<div class="error">Wrong username or password. Please try again.</div>');
                        div.hide()
                        $('.container_signin form').prepend(div);
                        div.fadeIn(1000);
                    }
                    signinAttempts++;
                }
            }
        });
    }

    function recoverPassword() {
        if (recoverPasswordProcessing) {
            return;
        }

        var errors = [];
        var _email = $("input[name=recover_email]");

        // is email populated
        if (!_email.val()) { errors.push("Please enter your e-mail address to receive instructions on how to reset your password."); }

        if (!errors.length) {
            recoverPasswordProcessing = true;
            $.ajax({
                type: "POST",
                url: WORKING_SERVER_PATH + "ajax/recoverpassword.asp",
                data: "recover_email=" + _email.val(),
                success: function (response) {
                    eval(response)
                    recoverPasswordProcessing = false;
                    if (response.status == "valid") {
                        var _email = $("input[name=recover_email]");
                        var div = $('<div class="success">Instructions to reset your password has been sent to ' + _email.val() + '</div>');
                        _email.val('');
                        div.hide();
                        $('.container_recoverpassword form .success').remove()
                        $('.container_recoverpassword form').prepend(div);
                        div.fadeIn(1000);
                    } else {
                        alert("Invalid e-mail address, please try again.");
                    }
                }
            });
        } else {
            alert(errors.join("\n"));
        }
    }




    // if the function argument is given to overlay,
    // it is assumed to be the onBeforeLoad event listener
    $("#submit_contact").click(function () {
        var errors = [];
        var _firstname = $("input[name=firstname]");
        var _lastname = $("input[name=lastname]");
        var _email = $("input[name=email]");
        var _phone = $("input[name=phone]");

        // is firstname populated
        if (!_firstname.val()) { errors.push("First Name is required"); }
        // is lastname populated
        if (!_lastname.val()) { errors.push("Last Name is required"); }
        // is email populated
        if (!_phone.val()) { errors.push("Phone number is required"); }
        //is state populated
        if (!_email.val()) { errors.push("Your e-mail address is required"); }
        // is captcha correct
        if (jcap() == false) { errors.push("Please enter the text as it's shown in the image"); }

        //alert("Form validation will occur when the form is clicked.");

        //if (error

        if (!errors.length) {
            var form_data = $('#form_contact').serialize();
            $(".container_requestaccess").html("<div style='font-size:24px;text-align:center;'>Processing. This may take a few minutes...</div>");

            $.ajax({
                type: "POST",
                url: WORKING_SERVER_PATH + "ajax/contact.asp",
                data: form_data,
                success: function (response) {
                    if (response == "success") {
                        $(".container_requestaccess").html("<div style='font-size:24px;text-align:center;'>Thank you for contacting us.<br>We will contact you soon.</div>")
                    } else {
                        $(".container_requestaccess").html("<div style='font-size:24px;text-align:center;'>There was an error, please contact us at 866-765-9227.</div>")
                    }
                    //alert(response);
                }
            });

            $('#submit_contact').fadeOut(300);
            $('#submit_contact_disabled').fadeIn(300);
        }

        else {
            alert(errors.join("\n"));
        }



    });

    $("#submit_resetpassword").click(function () {
        var errors = [];
        var _email = $("input[name=email]");
        var _password1 = $("input[name=password1]");
        var _password2 = $("input[name=password2]");

        if (!_email.val()) { errors.push("Confirm your e-mail address"); }
        if (!_password1.val()) { errors.push("Enter your new password"); }
        if (!_password2.val()) { errors.push("Confirm your new password"); }
        if (jcap() == false) { errors.push("Please enter the text as it's shown in the image"); }

        if (!errors.length) {
            $("#form_resetpassword").submit();
            /*$.ajax({
            type: "POST",
            url: "/polycarb/ajax/requestaccess.asp",
            data: $('#form_requestaccess').serialize(),
            success: function (response) {
            if (response == "success") {
            $(".container_requestaccess").html("<div style='font-size:24px;text-align:center;'>Thank you for your access request.</div>")
            } else {

            }
            //alert(response);
            }
            });*/
        } else {
            alert(errors.join("\n"));
        }

    });


    // if the function argument is given to overlay,
    // it is assumed to be the onBeforeLoad event listener
    $("#submit_requestaccess").click(function () {
        var errors = [];
        var _firstname = $("input[name=firstname]");
        var _lastname = $("input[name=lastname]");
        var _email = $("input[name=email]");
        var _state = $("select[name=state]");

        // is firstname populated
        if (!_firstname.val()) { errors.push("First Name is required"); }
        // is lastname populated
        if (!_lastname.val()) { errors.push("Last Name is required"); }
        // is email populated
        if (!_email.val()) { errors.push("Email is required"); }
        //is state populated
        if (!_state.val()) { errors.push("Your State is required"); }
        // is captcha correct
        if (jcap() == false) { errors.push("Please enter the text as it's shown in the image"); }

        //alert("Form validation will occur when the form is clicked.");

        //if (error

        if (!errors.length) {
            //alert($('#form_requestaccess').serialize());
            var form_data = $('#form_requestaccess').serialize();
            $(".container_requestaccess").html("<div style='font-size:24px;text-align:center;'>Processing. This may take a few minutes...</div>")
            $.ajax({
                type: "POST",
                url: WORKING_SERVER_PATH + "ajax/requestaccess2.asp",
                data: form_data,
                success: function (response) {
                    if (response == "success") {
                        $(".container_requestaccess").html("<div style='font-size:24px;text-align:center;'>Thank you for your access request.</div>")
                    } else {

                    }
                }
            });
        } else {
            alert(errors.join("\n"));
        }

    });


    $("img[rel]").overlay({
        mask: '#000',
        onBeforeLoad: function () {

            // grab wrapper element inside content
            var wrap = this.getOverlay().find("div.wrap");

            // load the page specified in the trigger
            if (wrap.is(":empty")) {
                wrap.html("test");
            }
        },
        onLoad: function () {
            signIn();
        }

    });

    function changeTab(opts) {
        elm = $(opts);
        $(".overlay_header .waternav li a").removeClass("selected");
        elm.addClass("selected");
        if (elm.attr("container") == 'requestaccess') {
            $("#overlay").stop().animate({ "height": "500px" });
        } else {
            $("#overlay").stop().animate({ "height": "300px" });
        }
        $(".overlay-container").hide();
        $(".container_" + elm.attr("container")).show();
    }

    function createDownloadLinkEvents() {
        $("a[sc_id]").click(function () {
            selectedFile = $(this).attr('sc');
            var id = $(this).attr('sc_id');
            $.ajax({
                type: "POST",
                url: WORKING_SERVER_PATH + "ajax/loadfile.asp",
                data: 'sc_id=' + id,
                success: function (response) {
                    eval(response)
                    if (response.status == 'approved') {

                        var file = response.file.replace("/polycarb/", "");

                        _gaq.push(['_setCustomVar',
                            1,
                            'User-ID',
                            loggedInUser.id,
                            1
                        ]);

                        _gaq.push(['_setCustomVar',
                            2,
                            'User-Name',
                            loggedInUser.firstname + " " + loggedInUser.lastname,
                            1
                        ]);

                        _gaq.push(['_trackEvent', 'PDF', 'Downloaded', file]);

                        /*_gaq.push(['_addTrans',
                        '1',            // order ID - required
                        'Poly-Carb',    // affiliation or store name
                        '1',            // total - required
                        '0',            // tax
                        '0',            // shipping
                        '',             // city
                        '',             // state or province
                        ''              // country
                        ]);

                        // add item might be called for every item in the shopping cart
                        // where your ecommerce engine loops through each item in the cart and
                        // prints out _addItem for each
                        _gaq.push(['_addItem',
                        '1',              // order ID - required
                        'PLYCRB-001',     // SKU/code - required
                        'Download (PDF)', // product name
                        response.file,    // category or variation
                        '1',              // unit price - required
                        '1'               // quantity - required
                        ]);
                        _gaq.push(['_trackTrans']); //submits transaction to the Analytics servers*/
                        window.open(response.file, "_blank");
                    } else {
                        if (typeof response.alt_message != 'undefined') {
                            $("#overlay_message .wrap").html(response.alt_message);
                            overlayMessage.overlay().load();
                        } else {

                            _gaq.push(['_trackEvent', 'PDF', 'Access Denied', ""]);

                            $("#overlay_message .wrap").html("<br>Your account currently does not have access to that file. Please contact your representative: " + response.rep + " for access. ");
                            overlayMessage.overlay().load();
                        }
                    }
                }
            });
        });
    }

    overlayMessage = $("#overlay_message").overlay({
        mask: '#000',
        onBeforeLoad: function () {
            // grab wrapper element inside content
            var wrap = this.getOverlay().find("div.wrap");

            // load the page specified in the trigger
            //if (wrap.is(":empty")) {
            //    wrap.load("hello world");
            //}
        },
        load: false,
        onLoad: function () {

        }
    });

    videoOverlay = $("#video_overlay").overlay({
        mask: '#000',
        onBeforeLoad: function () {
            // grab wrapper element inside content
            var wrap = this.getOverlay().find("div.wrap");

            // load the page specified in the trigger
            //if (wrap.is(":empty")) {
            //    wrap.load("hello world");
            //}
        },
        load: false,
        onLoad: function () {

        }
    });

    mainOverlay = $("a[rel]").overlay({
        mask: '#000',
        onBeforeLoad: function () {
            // grab wrapper element inside content
            var wrap = this.getOverlay().find("div.wrap");

            // load the page specified in the trigger
            if (wrap.is(":empty")) {
                wrap.load(this.getTrigger().attr("file"));
            }
        },
        onLoad: function () {
            $('.container_signin .input[type=password]').keyup(function (e) {
                if (e.keyCode == 13) {
                    signIn();
                }
            });


            $('.signin_file_to_load').val(selectedFile);
            $(".overlay_header .waternav li a").click(function () {
                changeTab(this);
            });
            signinAttempts = 0;
            selectedFile = '';
            // Sign In: AJAX call when submit button is pressed				
            $("#submit_signin").click(function () {
                signIn();
            });

            $('.container_recoverpassword .input').keyup(function (e) {
                if (e.keyCode == 13) {
                    recoverPassword();
                }
            });

            recoverPasswordProcessing = false;
            $("#submit_recoverpassword").click(function () {
                recoverPassword();
            });

        }

    });

    $("#logout").click(function () {
        $.ajax({
            type: "POST",
            url: WORKING_SERVER_PATH + "ajax/logout.asp",
            data: '',
            success: function (response) {
                window.location.reload(true);
            }
        });
    });


    $(".error_signin").live('click', function () {
        overlayMessage.overlay().close();
        setTimeout("mainOverlay.overlay().load();", 700);

    });

    $('.disclaimer').appendTo($('.content-A'));
    $('.disclaimer').show();

    createDownloadLinkEvents();

});
