$(document).ready(function () {
    // Main Navigation
    $('.navigation ul:not(.navigation_selected)').hide();
    $('.navigation .navigation_selected').parents('li:not(.navigation ul li)').addClass('minus');
    $('.navigation li').not('.navigation ul li').prepend('<span class="clicks"></span>');
    $('.navigation .clicks').toggle(
    function () { $(this).next().next().show('fast'); $(this).parent().addClass('minus'); },
    function () { $(this).next().next().hide('fast'); $(this).parent().removeClass('minus'); });

    $('.navigation .clicks').hover(
    function () { $(this).parent().addClass('glow'); },
    function () {
        $(this).parent().removeClass('glow');
    });

    //Exists by selector. Ex.: if ($.exists('.test')) {.}
    jQuery.exists = function (selector) { return ($(selector).length > 0); }

    $.fn.delay = function (time, callback) {
        jQuery.fx.step.delay = function () { };
        return this.animate({ delay: 1 }, time, callback);
    }

    // RFP Form
    if ($.exists('.rfpForm')) {
        var FNameDefault = "Name*";
        var FCompanyDefault = "Company";
        var FPhoneDefault = "Phone";
        var FAddinfoDefault = "How can we help you?*";
        var FMailDefault = "Email*";

        function popupFocus(id, defaultText) {
            $(id).focusin(function () {
                if ($(this).val() == defaultText) {
                    $(this).val('');
                }
            });
            $(id).focusout(function () {
                if ($(this).val() == '') {
                    $(this).val(defaultText);
                }
            });
        }

        popupFocus("#FName", FNameDefault);
        popupFocus("#FCompany", FCompanyDefault);
        popupFocus("#FMail", FMailDefault);
        popupFocus("#FPhone", FPhoneDefault);
        popupFocus("#FAddinfo", FAddinfoDefault);

        $('#rfpGo').hover(
        function () {
            $(".submit1").css("background-position", "0px -27px");
        },
        function () {
            $(".submit1").css("background-position", "0px 0px");
        });

        /*------------*/
        function rfpGo() {
            if (checkForm() == true) {
                if (document.forms.JobPost.onsubmit()) {
                    var dataString = "";
                    $(".rfpForm input,textarea").each(function (i) { dataString += this.name + "=" + escape(this.value) + "&" });

                    $(".hideable").animate({
                        opacity: 0
                    }, 250);
                    $(".hideable").queue(function () {
                        $(".afterButton").append('<div style="display:inline;"><img height="1" width="1" style="border-style:none;" alt="" src=""/></div>');
                        $(".afterButton").css('opacity', '0');
                        $(".hideable").css('visibility', 'hidden');
                        $("#rfpGo").css('visibility', 'hidden');
                        $(".afterButton").css('visibility', 'visible');
                        $(".hideable").clearQueue();
                        $(".afterButton").animate({
                            opacity: 1
                        }, 250);
                        $(".afterButton").clearQueue();
                    });

                    $.ajax({
                        type: "POST",
                        url: "/quick_contact.php",
                        data: dataString,
                        success: function () {
                            try { trackForm('RFP'); } catch (e) { }
                        }
                    });
                }
            }
        }
        $("#FName, #FCompany, #FMail, #FPhone").keydown(function (e) {
            if (e.keyCode == 13) {
                rfpGo();
            }
        });

        $("#FAddinfo, #FName, #FCompany, #FMail, #FPhone").keydown(function (e) {
            if (e.ctrlKey && e.keyCode == 13) {
                rfpGo();
            }
        });

        $("#rfpGo").click(function () {
            rfpGo();
        });

        $("#submit1").click(function () {
            rfpGo();
        });


        $("#showRFP").click(function () {
            $(".afterButton").animate({
                opacity: 0
            }, 250);
            $(".afterButton").queue(function () {
                $(".hideable").css('opacity', '0');
                $(".hideable").css('visibility', 'visible');
                $("#rfpGo").css('visibility', 'visible');
                $(".afterButton").css('visibility', 'hidden');
                $(".afterButton").clearQueue();
                $(".hideable").animate({
                    opacity: 1
                }, 250);
                $(".hideable").clearQueue();
                $("#FName").val("Name*");
                $("#FCompany").val("Company*");
                $("#FMail").val("Email*");
                $("#FPhone").val("Phone");
                $("#FAddinfo").val("How can we help you?*");
            });
        });

        function checkOnlySpaces(string) {
            var i = 0;
            var result = 0;
            for (i = 0; i < string.length; i++) {
                if (string.charAt(i) == " ") {
                    result++;
                }
            }
            if (result == i) {
                return true;
            } else {
                return false;
            }
        }

        function emailValid(string) {
            var rege = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
            if (rege.test(string)) {
                return true;
            } else {
                return false;
            }
        }

        function displayError(element, message) {
            if ($(element).parent().prev().css("display") == "none") {
                $(element).parent().prev().html(message);
                blockHeight = $(".rfpForm").height() + 10;
                $(".rfpForm").height(blockHeight);
                $(element).parent().prev().css({ "display": "block" });
                $(element).parent().prev().animate({
                    opacity: 1
                }, 400);
                $(element).parent().prev().clearQueue();
            } else if ($(element).parent().prev().css("display") == "block") {
                $(element).parent().prev().html(message);
            }
        }

        function errorNotify(element, elementValue, emailCheck) {
            var error = 0;
            if ($(element).val() == "" || $(element).val() == elementValue) {   // if empty or default value
                error++;
                displayError(element, "Please fill this field");
            } else if (checkOnlySpaces($(element).val()) == true) { // else if only spaces detected
                error++;
                displayError(element, "Please enter valid symbols");
            } else if (emailCheck == true && emailValid($(element).val()) == false) {  // else if email not valid
                error++;
                displayError(element, "Please enter valid email");
            } else { // else
                if ($(element).parent().prev().css("display") == "block") {
                    blockHeight = $(".rfpForm").height() - 10;
                    $(".rfpForm").height(blockHeight);
                    $(element).parent().prev().css({ "display": "none" });
                }
            }
            return error;
        }

        function checkForm() {
            var error = 0;
            error += errorNotify("#FName", "Name*", false);
            error += errorNotify("#FMail", "Email*", true);
            error += errorNotify("#FAddinfo", "How can we help you?*", false);
            if (error == 0) {
                return true;
            } else {
                return false;
            }
        }
    }

    // Clients Scroll Box
    if ($.exists('.spinbox')) {
        $.getScript("/js/jquery.scrollTo.js", function () {
            var spinWidth = 177;
            if ($.exists('.spinclients')) spinWidth = 200;
            var spinPos = 0;
            var spinSpeed = 800;
            var spinStop = 1;
            var spinEls = $('.spinbox td').size();
            var spinTotal = spinEls * spinWidth;
            var spinPosEnd = spinTotal - spinWidth;
            var spinAutoSpeed = 8000;
            if (spinEls < 3) spinAutoSpeed = 7000;

            if ($.exists('.spingetimages')) {
                var spinRel = $('.spinbox td a');
                spinRel[0].innerHTML = '<img src="' + spinRel[0].getAttribute('rel') + '" alt="' + spinRel[0].getAttribute('title') + '" />';
            }

            $('.spinbox table').css('width', spinTotal + 'px');
            if (spinEls > 1) {
                $('.larrow, .rarrow').hover(function () { $(this).addClass('glow'); }, function () { $(this).removeClass('glow'); });
                $('.larrow, .rarrow').mouseup(function () { $(this).removeClass('opac'); }).mousedown(function () { $(this).addClass('opac'); });
                $('.spinbox td, .spin span').hover(function () { spinStop = 0; }, function () { spinStop = 1; });
                $('.larrow').click(function () { spinleft() });
                $('.rarrow').click(function () { spinright() });
            }
            spinleft = function () {
                if (spinPos >= spinWidth && spinPos > 0) { spinPos += -spinWidth; spinSpeed = 800; }
                else { spinPos = spinPosEnd; if (spinEls > 2) spinSpeed = 0; }
                spin();
            }
            spinright = function () {
                if (spinPos <= spinPosEnd) {
                    if (spinPos == spinPosEnd) { spinPos = 0; if (spinEls > 2) spinSpeed = 0; }
                    else { spinPos += spinWidth; spinSpeed = 800; }
                }
                spin();
            }
            spin = function () {
                if ($.exists('.spingetimages')) {
                    var sCur = (spinPos / spinWidth);
                    spinRel[sCur].innerHTML = '<img src="' + spinRel[sCur].getAttribute('rel') + '" alt="' + spinRel[sCur].getAttribute('title') + '" />';
                    if (spinRel[sCur + 1]) { new Image().src = spinRel[sCur + 1].getAttribute('rel'); }
                }
                $('.spinbox').scrollTo(spinPos, spinSpeed);
            }
            autoSpin = function () {
                if (spinStop) { spinright(); }
                setTimeout(autoSpin, spinAutoSpeed);
            }
            setTimeout(autoSpin, spinAutoSpeed);
        });
    }

    //Colorise footer icons
    $('.footer .awards img').hover(function () { $(this).attr('src', this.src.replace('.png', '-color.png')); }, function () { $(this).attr('src', this.src.replace('-color.png', '.png')); });

    if (!$('#tMenu').is(':empty')) {
        $.getScript("/media/js/jquery.tooltip.js", function () {
            $(".header .logo, #tMenu").ezpz_tooltip({
                contentPosition: 'belowStatic',
                stayOnContent: true,
                contentId: 'tMenu',
                offset: 0
            });
        });
    }

    if ($.exists("a[rel='zoom']")) { $.getScript("/js/jquery.lightbox.js", function () { $("a[rel='zoom']").lightBox(); }); }

    // load fancybox for RFP-popup
    if ($.exists("a[rel='showRFP']")) {
        var css;

        // include fancybox.css
        $("head").append("<link>");
        css = $("head").children(":last");
        css.attr({ rel: "stylesheet", type: "text/css", href: "/css/jquery.fancybox-1.3.4.css" });

        // include rfp-popup.css
        $("head").append("<link>"); 
        css = $("head").children(":last");
        css.attr({ rel: "stylesheet", type: "text/css", href: "/css/rfp-popup.css" });

        $("a[rel='showRFP']").attr("href", "#rfp-popup"); // change <a> href if rel='showRFP'

        // include rfp-popup code in to the html        
        $.ajax({
            url: "/pages/rfp-popup-code.html",
            cache: false,
            success: function (data) {
                $("body").prepend(data);
            }
        });

        // include fancybox plugin. Go!
        $.getScript("/js/jquery.fancybox-1.3.4.pack.js", function () {            
            // include rfp-popup js.
            $.getScript("/js/rfp-popup.js");
            $("a[rel='showRFP']").fancybox({
                'scrolling': 'no',
                'showCloseButton': true,
                'speedIn': 400,
                'speedOut': 200,
                'cyclic': false,
                'padding': '0',
                'showNavArrows': false,
                onStart: function () {
                    // fill all fields with default values. default values included from /js/rfp-popup.js
                    $("#popup-name").val(nameDefault);
                    $("#popup-company").val(companyDefault);
                    $("#popup-phone").val(phoneDefault);
                    $("#popup-additional").val(additionalDefault);
                    $("#popup-email").val(emailDefault);
                    // hide errors
                    $(".rfp-popup #popup-name, .rfp-popup #popup-company, .rfp-popup #popup-email, .rfp-popup #popup-additional").parent().removeClass("error");
                    // show popup window
                    $(".rfp-popup").css("display", "block");
                },
                onCleanup: function () {
                    // hide popup window
                    $(".rfp-popup").css("display", "none");
                }
            });
        });
    }

});

function setLeedVar()
{
 pageTracker._setCustomVar(
 1, // This custom var is set to slot #1
 "User Type", // The name of the custom variable
 "Lead", // The value of the custom variable
 // (possible values might be Free, Bronze, Gold, and Platinum)
 1 // Sets the scope to visitor-level
 );
}

function trackEMail( id )
{
 setLeedVar();

 pageTracker._trackPageview("/contact-by-email/" + id);
}

function trackForm( id )
{
 setLeedVar();

 pageTracker._trackPageview("/contact-by-form/" + id);
}


function captchaError(errorDiv)
{
 var input = document.getElementById('captcha_input');
 var hash = document.getElementById('CaptchaHash');
 var error = document.getElementById(errorDiv);
 if ( error != null )
 error.style.display = 'none';

 var hashValue = 0;
 var hashText = input.value.toLowerCase();
 for ( var i = 0; i < hashText.length; i++ )
 {
 hashValue = hashValue + hashText.charCodeAt(i);
 }

 if ( hashValue != hash.value )
 {
 if (error != null)
 error.style.display = 'block';
 else
 alert("Wrong verification code!");
 return false;
 }
 return true;
}
function checkLength( id )
{
var e = document.getElementById(id);
if (e)
{
if ( e.value.length > 1000 ) e.value = e.value.substring(0, 1000);
}
return true;
}

