// jQuery No Conflict
var $j = jQuery.noConflict();


$j(document).ready(function() {
    //--------------------------------------------------------------------
    // fires when the DOM is ready
    //--------------------------------------------------------------------

    topSearch();
    extWindows();

    //Disable enter key for all pages (gets enabled again when focusing search box)
    $j("input", $j("#aspnetForm")).keypress(function(event) {
        if (event.keyCode == '13') {
            event.preventDefault();
        }
    });

    // CLIENT CARROUSEL
    if ($j('.clc').length) {
        $j('div.clc').load('clientlogos.html', '', function() {
            $j('#mycarousel').jcarousel({
                easing: 'easeOutBack',
                animation: 1000,
                auto: 6,
                wrap: 'last'
                // itemLoadCallback: mycarousel_itemLoadCallback
            });
        });
    }

    // LANGUAGE BAR ROLL OVER
    $j("span.language a").hover(function() {
        $j("div.langbar").slideDown('fast').show();

        $j("div.langbar").hover(function() {
        }, function() {
            $j("div.langbar").slideUp('slow');
        });
    }).hover(function() {
        $j(this).addClass("subhover");
    }, function() {
        $j(this).removeClass("subhover");
    });


    //    MAIN NAV ROLL (not used)

    //    function addMega() {
    //        $j(this).addClass("subhover");
    //    }

    //    function removeMega() {
    //        $j(this).removeClass("subhover");
    //    }

    //    var megaConfig = {
    //        interval: 100,
    //        sensitivity: 7,
    //        over: addMega,
    //        timeout: 0,
    //        out: removeMega
    //    };

    //    $j("ul.mainav li").hoverIntent(megaConfig)

    //    var zIndexNumber = 1000;
    //    $j('ul.mainav li div').each(function() {
    //        $j(this).css('zIndex', zIndexNumber);
    //        zIndexNumber -= 10;
    //    });

    ///

    // SIDEBAR INIT
    //    $j("dd").hide();
    //    $j("dt a").click(function() {
    //        $j("dd:visible").slideUp("slow");
    //        $j(this).parent().next().slideDown("slow");
    //        return false;
    //    });


    // $j("dd:eq(0)").slideDown("slow");
    return false;

    //--------------------------------------------------------------------
    // end of DOM ready script
    //--------------------------------------------------------------------
});


// topSearch() takes the label and puts it into the searchfield and hides it on focus
function topSearch() {
    $j(".search_box").css("display", "none");
    topSearchText = $j(".s").val();
    //    $(".topSearch :text").val(topSearchText);
    //    $(".topSearch label").hide();
    $j(".s").focus(function() {
        if ($j(this).val() == topSearchText) {
            $j(this).val("");
        }
        $j("#aspnetForm").keypress(function(event) {
            if (event.keyCode == '13') {
                event.preventDefault();
                $j(".go").click()
            }
        });
    });
    $j(".s").blur(function() {
        if ($j(this).val() == "") {
            $j(this).val(topSearchText);
        }
        $j("#aspnetForm").keypress(function(event) {
            if (event.keyCode == '13') {
                event.preventDefault();
            }
        });
    });
    $j(".search_box").css("display", "block");
}

// extWindows() makes links open in a different window. use rel="external" instead of target="_blank" and rel="popup" or rel="popup|[width]|[height]" for popups
function extWindows() {
    $j("a[rel*=external]").attr("target", "_blank");
    $j("a[rel^=popup]").click(function() {
        theHref = $j(this).attr("href");
        //		$(this).attr("href","javascript:void(0)");
        var popupWidth, popupHeight
        var relSplit = $j(this).attr("rel").split("|");
        if (relSplit[1]) {
            popupWidth = relSplit[1];
            popupHeight = relSplit[2];
        } else {
            popupWidth = 435;
            popupHeight = 350;
        }
        popMeUp(theHref, popupWidth, popupHeight)
        return false;
    });
}
//Opens a popup window
function popMeUp(strURL, strWidth, strHeight) {
    theWin = window.open(strURL, "popupWin", "scrollbars,resizable,height=" + strHeight + ",width=" + strWidth);
    theWin.focus();
}


//Arranges the register form in three parts and disables either org number or vat number, as appropriate
var theFieldSet = 0
function checkIfTabs() {
    if ($j(".signUpForm fieldset").length > 1) {
        $j(".signUpForm fieldset:first").before('<div class="leftCorner"></div><div class="rightCorner"></div><ul class="fieldNav"></ul>')

        $j(".signUpForm fieldset").each(function() {
            $j(".fieldNav").append('<li>' + $j(this).attr("title") + '</li>')
            $j(this).hide()
        })
//        The links on the top of the page arent clickable anymore. 
//        $j(".signUpForm ul.fieldNav li").each(function(i) {
//        var i = i
//            $j(this).click(function() {
//                goFieldSet(i);
//                //theFieldSet = i
//            })
//        });
        $j(".signUpForm fieldset:first").show()
        $j(".signUpForm ul.fieldNav li:first").addClass("active")
        $j(".signUpForm fieldset:last legend").after('<div id="theSubMitString"></div>')
        $j("#Country").change(function() {
            resetLanguageFields();
            if ($j(this).val() == "SE") {
                $j("#OrgNumber").removeAttr("disabled")
                $j("#OrgNumber").removeClass("tentative")
                $j("#OrgNumber").parents("p").removeClass("disabled")
                $j("#OrgNumber").removeClass("disabled")
                $j("#Vat").addClass("disabled")
                $j("#Vat").attr("disabled", true)
                $j("#Vat").parents("p").addClass("disabled")
                $j("#Vat").val("")
                checkVat();
            } else if ($j(this).val() == "US") {
                $j("#County").val("")
                $j("#County").addClass("hidden")
                $j("#CountyTitleText").addClass("hidden")
                $j("#StateTitleText").removeClass("hidden")
                $j("#CountyErrorText").addClass("hidden")
                $j("#StateErrorText").removeClass("hidden")
                $j("#State").removeClass("hidden")
                $j("#State").removeClass("tentative")
                $j("#OrgNumber").parent("div").addClass("hidden")
                $j("#Vat").parent("div").addClass("hidden")
                $j("#Vat").val("")
            }
        })
        $j("#Vat").blur(function() {
            checkVat();
        });
    }
}
function resetLanguageFields() {
    $j("#County").removeClass("hidden")
    $j("#State").addClass("hidden")
    $j("#State").addClass("tentative")
    $j("#CountyTitleText").removeClass("hidden")
    $j("#StateTitleText").addClass("hidden")
    $j("#CountyErrorText").removeClass("hidden")
    $j("#StateErrorText").addClass("hidden")
    $j("#County").parent("div").removeClass("error");
    $j("#County").parent("div").find(".validation").hide()

    $j("#Vat").parent("div").removeClass("hidden")
    $j("#Vat").removeAttr("disabled")
    $j("#Vat").parents("p").removeClass("disabled")
    $j("#Vat").removeClass("disabled")

    $j("#OrgNumber").parent("div").removeClass("hidden")
    $j("#OrgNumber").attr("disabled", true)
    $j("#OrgNumber").addClass("tentative")
    $j("#OrgNumber").addClass("disabled")
    $j("#OrgNumber").parents("p").addClass("disabled")
    $j("#OrgNumber").val("")
    $j("#OrgNumber").parent("div").removeClass("error");
    $j("#OrgNumber").parent("div").find(".validation").hide()
    $j("#OrgNumber").parent("div").find(".validationSpecial").hide()
}
//Switching between fieldsets
//theField was the number of the set you are leaving, and it will be checked so all data are correct
//i is the number of the field you are entering, and it will be made visible
function goFieldSet(i) {
    theField = theFieldSet;
    var returnValue = "true";
    if (theField < i) {
        var mailPattern = /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
        var orgnrPattern = /^((\d{6,6})-?(\d{4,4}))$/;
        $j(".signUpForm fieldset:eq(" + theField + ")").find(":input").each(function() {
            if ((($j(this).val() == "") || ($j(this).val() == -1)) && (!$j(this).hasClass("tentative"))) {
                $j(this).parent("div").addClass("error")
                $j(this).parent("div").find(".validation").css("display", "block")
                returnValue = "false"
            } else if (($j(this).attr("id") == "Email") && (mailPattern).test($j(this).val()) == false) {
                $j(this).parent("div").addClass("error")
                $j(this).parent("div").find(".validation").hide()
                $j(this).parent("div").find(".validationSpecial").css("display", "block")
                returnValue = "false"
            } else if (($j(this).attr("id") == "OrgNumber") && (orgnrPattern).test($j(this).val()) == false && !$j(this).hasClass("tentative")) {
                $j(this).parent("div").addClass("error")
                $j(this).parent("div").find(".validation").hide()
                $j(this).parent("div").find(".validationSpecial").css("display", "block")
                returnValue = "false"
            } else {
                $j(this).parent("div").removeClass("error");
                $j(this).parent("div").find(".validation").hide()
                $j(this).parent("div").find(".validationSpecial").hide()
            }
        })
    }
    if (returnValue == "true") {
        theField = i;
        theFieldSet = i;
        $j(".signUpForm fieldset").hide();
        $j(".signUpForm fieldset:eq(" + i + ")").show();
        $j(".signUpForm ul.fieldNav li").removeClass("active")
        $j(".signUpForm ul.fieldNav li:eq(" + i + ")").addClass("active")
        filloutBlanks()
        $j("html,body").animate({ scrollTop: $j(".signUpForm").offset().top - 5 }, 500);
    }
}

function checkVat() {
    theVat = $j("#Vat");
    if ($j.trim(theVat.val()) != "") {
        theVatString = $j("#Country").val() + "/" + $j("#Vat").val().replace(/\D/g, "");
        $j.getJSON('http://isvat.appspot.com/' + theVatString + '/?callback=?', function(data) {
            if (!data && !data.error) {
                theVat.parent("div").addClass("error")
                theVat.parent("div").find(".validation").hide()
                theVat.parent("div").find(".validationSpecial").css("display", "block")
            } else {
                theVat.parent("div").removeClass("error");
                theVat.parent("div").find(".validation").hide()
                theVat.parent("div").find(".validationSpecial").hide()
            }
        });
    } else {
        theVat.parent("div").removeClass("error");
        theVat.parent("div").find(".validation").hide()
        theVat.parent("div").find(".validationSpecial").hide()
    }
}
var theSubmitString
function filloutBlanks() {
    theSubmitString = "";
    $j(".signUpForm label").each(function() {
        var theName = $j(".inputName", this).text();
        var theValue = $j(this).parent().next().val();
        var theInputName = $j(this).parent().next().get()[0].name;

        if (jQuery.trim(theName) == "")
        { }
        else if (theInputName == "County") {
            if ($j("#Country").val() == "US") {
                theName = $j("#StateTitleText").text();
                theValue = $j("#State").val();
                if (theValue == "-1") theValue = "";
            }
            else {
                theName = $j("#CountyTitleText").text();
                theValue = $j("#County").val();
            }
            theSubmitString += '<div><p>' + theName + '</p><span class="signUpInput">' + theValue + '</span></div><div class="clear"></div>';
        }
        else if (theInputName == "Vat" && $j("#Country").val() == "US") {
            //USA cant fill in vat
        }
        else if (theInputName == "OrgNumber" && $j("#Country").val() == "US") {
            //USA cant fill in orgnumber
        }
        else if (jQuery.trim(theValue) == "") {
            theSubmitString += '<div><p>' + theName + '</p></div><div class="clear"></div>';
        }
        else {
            switch (theInputName) {
                case "Industry": // id|name
                    if (theValue.indexOf("|") != -1)
                        theValue = theValue.split("|")[1];
                default:
                    theSubmitString += '<div><p>' + theName + '</p><span class="signUpInput">' + theValue + '</span></div><div class="clear"></div>';
            }
        }
    })
    $j("span.inputP").html(theSubmitString)
}
var formIsSubmitted = false;
function submitForm() {
    if (($j("#conFirmMe").size() > 0) && ($j("#conFirmMe").attr("checked") != true)) {
        $j("#conFirmMe").parent("p").parent("div").addClass("error")
        $j("#conFirmMe").parent("p").parent("div").find(".validation").css("display", "block")
    }
    else if (!formIsSubmitted) {
        formIsSubmitted = true;
        $j("form").submit();
    }
}
function createTrackbackLink(targetdiv) {
    var target = $j("#" + targetdiv);
    target.html(target.html().replace("***webhostname***", window.location.hostname))
    target.removeClass("hidden");
}
