function initPage()
{
// GJS -- just changed passwordFieldText to false -- 
// not sure what this is for, but causing display issues
/*
	clearFormFields({
		clearInputs: true,
		clearTextareas: true,
		passwordFieldText: false,
		addClassFocus: "focus",
		filterClass: "default"
	});*/
}
function clearFormFields(o)
{
    if (o.clearInputs == null) o.clearInputs = true;
    if (o.clearTextareas == null) o.clearTextareas = true;
    if (o.passwordFieldText == null) o.passwordFieldText = false;
    if (o.addClassFocus == null) o.addClassFocus = false;
    if (!o.filter) o.filter = "default";
    if(o.clearInputs) {
        var inputs = document.getElementsByTagName("input");
        for (var i = 0; i < inputs.length; i++ ) {
            if((inputs[i].type == "text" || inputs[i].type == "password") && inputs[i].className.indexOf(o.filterClass)) {
                inputs[i].valueHtml = inputs[i].value;
                inputs[i].onfocus = function ()	{
                    if(this.valueHtml == this.value) this.value = "";
                    if(this.fake) {
                        inputsSwap(this, this.previousSibling);
                        this.previousSibling.focus();
                    }
                    if(o.addClassFocus && !this.fake) {
                        this.className += " " + o.addClassFocus;
                        this.parentNode.className += " parent-" + o.addClassFocus;
                    }
                }
                inputs[i].onblur = function () {
                    if(this.value == "") {
                        this.value = this.valueHtml;
                        if(o.passwordFieldText && this.type == "password") inputsSwap(this, this.nextSibling);
                    }
                    if(o.addClassFocus) {
                        this.className = this.className.replace(o.addClassFocus, "");
                        this.parentNode.className = this.parentNode.className.replace("parent-"+o.addClassFocus, "");
                    }
                }
                if(o.passwordFieldText && inputs[i].type == "password") {
                    var fakeInput = document.createElement("input");
                    fakeInput.type = "text";
                    fakeInput.value = inputs[i].value;
                    fakeInput.className = inputs[i].className;
                    fakeInput.fake = true;
                    inputs[i].parentNode.insertBefore(fakeInput, inputs[i].nextSibling);
                    inputsSwap(inputs[i], null);
                }
            }
        }
    }
    if(o.clearTextareas) {
        var textareas = document.getElementsByTagName("textarea");
        for(var i=0; i<textareas.length; i++) {
            if(textareas[i].className.indexOf(o.filterClass)) {
                textareas[i].valueHtml = textareas[i].value;
                textareas[i].onfocus = function() {
                    if(this.value == this.valueHtml) this.value = "";
                    if(o.addClassFocus) {
                        this.className += " " + o.addClassFocus;
                        this.parentNode.className += " parent-" + o.addClassFocus;
                    }
                }
                textareas[i].onblur = function() {
                    if(this.value == "") this.value = this.valueHtml;
                    if(o.addClassFocus) {
                        this.className = this.className.replace(o.addClassFocus, "");
                        this.parentNode.className = this.parentNode.className.replace("parent-"+o.addClassFocus, "");
                    }
                }
            }
        }
    }
    function inputsSwap(el, el2) {
        if(el) el.style.display = "none";
        if(el2) el2.style.display = "inline";
    }
}
if (window.addEventListener)
    window.addEventListener("load", initPage, false);
else if (window.attachEvent)
    window.attachEvent("onload", initPage);

$(document).ready(function(){        
    /* DEMO DOWNLOADS */
    loadDemo();
    if($("#demo-download-form").length > 0){
        $(".download-demo").live("click", function(){
            checkBoxes(this);
        });
        $(".selected-checkbox").live("change", function(){
            selectLi(this);
        });
        $(".check-all").live("click", function(){
            checkAllDemos(this);
        });
        $(".uncheck-all").live("click", function(){
            uncheckAllDemos(this);
        });
    $("#demo-download-submit").click(function(){
                /*if($(".demo-data-required").length > 0) {
                    if($(".demo-data-required").find(".required").val() != ''){
                        $(".demo-data-required").parent("div").find(".errorMessage").hide();
                        $(".demo-data-required").find(".required").removeClass("error");
                        //Do nothing
                    }else{
                        $(".demo-data-required").find(".required").addClass("error").fadeTo("fast", 0.4).fadeTo("fast", 1);
                        $(".demo-data-required").parent("div").find(".errorMessage").fadeTo("fast", 0.4).fadeTo("fast", 1);
                        return false;
                    }
                }*/
            });
    }
    /* Check Required Fields */
    $(".check-form").live("click", function(){
       var pass = true; 
       $(this).closest("form").find(".required").each(function(){
           if($(this).val()==''){
               $(this).addClass("errorInput").fadeTo("fast", 0.3).fadeTo("fast", 1);
               $(this).closest("form").find(".errorSummary").fadeIn("fast");
               if(pass){
                   pass = false;
               }
           }else{
               $(this).removeClass("errorInput");
           }
       });
       if(!pass){
           return false;           
       }
    });
    $(".errorInput").live("focus", function(){
       $(this).removeClass("errorInput"); 
    });
    /* Remove Demo */
    $(".clearDemo").click(function(){
        var _this = this;
        $(_this).closest(".demo-download-wrap-2").fadeTo("fast", 0.6);
        $.ajax({
            url: $(this).attr("href"),
            success: function(){
                $(_this).closest(".demo-download-wrap-2").fadeOut("slow").remove();
            }
        }); 
    });
    /* TABSET */
    if($('.tabset').length > 0){
        $('.tabset').tabs();
    }
    if($(".customer-type").length > 0){
        toggleCustomerType();
    }
    if($("#load-twitter").length > 0){
        getTwitter();
    }
    if($("#tab-set").length > 0){
        checkTabs();
    }
    if($("#related_item_list").length > 0){
        checkRelatedItems();
    }
    $("#toggle-shipping").bind("change", function(){
        if($(".toggle-me").is(":visible")){
            $(".toggle-me").slideUp();
        }else{
            $(".toggle-me").slideDown();
        }
    });
    if($("#toggle-shipping").length > 0){
        if($("#toggle-shipping").is(":checked")){
            $(".toggle-me").slideDown();
        }
    }
    if($("input:radio[name=gateway]").length > 0){
        $("input:radio[name=gateway]").bind('change', function(){
            if($("input:radio[@name=gateway]:checked").val() == 0){
                $(".content-section-overlay").fadeOut();
            }else{
                $(".content-section-overlay").fadeTo('fast', 0.6);
            }
        });
    }

    if($("#copy-address-info")){
        $("#copy-address-info").click(function(){
            if($("#BillingAddressForm_country").val()!='US'){
                $("#state-option-wrap-2").empty();
                $("#state-option-wrap-2").append('<input type="text" id="ShippingAddressForm_state" name="ShippingAddressForm[state]" class="text-input" />');
                changeS = true;                
            }else{
                $("#state-option-wrap-2").empty();
                $("#state-option-wrap-2").append(originalShippingStateDropdown);                    
            }
            $("#billingAddressForm").children().each(function(){
                $(this).children().each(function(){
                    if($(this).is(":input")){
                        var id = $(this).attr("id");
                        id = id.replace("BillingAddressForm_", "ShippingAddressForm_");
                        $("#"+id).val($(this).val());
                    }else{
                        $(this).children().each(function(){
                            if($(this).is(":input")){
                                var id = $(this).attr("id");
                                id = id.replace("BillingAddressForm_", "ShippingAddressForm_");
                                $("#"+id).val($(this).val());
                            }else{
                                $(this).children().each(function(){
                                    if($(this).is(":input")){
                                        var id = $(this).attr("id");
                                        id = id.replace("BillingAddressForm_", "ShippingAddressForm_");
                                        $("#"+id).val($(this).val());
                                    }
                                });
                            }
                        });
                    }
                });
            });
        });
    }
    if($("#BillingAddressForm_state")){
            if($("#international-billing").length > 0){
                originalBillingStateDropdown = $("#international-billing").find("#BillingAddressForm_state");
                $("#international-billing").find("#BillingAddressForm_state").remove();
                change = true;
            }else{
                originalBillingStateDropdown = $("#BillingAddressForm_state");
                change = false;
            }
            
            if($("#international-shipping").length > 0){
                originalShippingStateDropdown = $("#international-shipping").find("#ShippingAddressForm_state");
                $("#international-shipping").find("#ShippingAddressForm_state").remove();
                changeS = true;
            }else{
                originalShippingStateDropdown = $("#ShippingAddressForm_state");                
                changeS = false;
            }
            
            if($("#international-licensee").length > 0){
                originalLicenseeStateDropdown = $("#international-licensee").find("#LicenseeAddressForm_state");
                $("#licensee-shipping").find("#LicenseeAddressForm_state").remove();
                changeL = true;
            }else{
                originalLicenseeStateDropdown = $("#LicenseeAddressForm_state");                
                changeL = false;
            }
    }
    $(".country-dropdown-2").bind("change", function(){
        if(changeS){
            $("#ShippingAddressForm_state").remove();
            $("#state-option-wrap-2").append(originalShippingStateDropdown);
        }
        if($("#ShippingAddressForm_state")){
            if($(this).val() != 'US'){
                $("#ShippingAddressForm_state").remove();
                $("#state-option-wrap-2").append('<input type="text" id="ShippingAddressForm_state" name="ShippingAddressForm[state]" class="text-input" />');
                changeS = true;
            }
        }
    });
    $(".country-dropdown").bind("change", function(){

        if(change){
            $("#BillingAddressForm_state").remove();
            $("#state-option-wrap").append(originalBillingStateDropdown);
        }

        if($(this).val() != 'US'){
            $("#BillingAddressForm_state").remove();
            $("#state-option-wrap").append('<input type="text" id="BillingAddressForm_state" name="BillingAddressForm[state]" class="text-input" />');                
            change = true;
        }else{
            change = false;
        }
    });
    $(".country-dropdown-2").bind("change", function(){

        if(changeS){
            $("#ShippingAddressForm_state").remove();
            $("#state-option-wrap-2").append(originalShippingStateDropdown);
        }

        if($(this).val() != 'US'){
            $("#ShippingAddressForm_state").remove();
            $("#state-option-wrap-2").append('<input type="text" id="ShippingAddressForm_state" name="ShippingAddressForm[state]" class="text-input" />');                
            changeS = true;
        }else{
            changeS = false;
        }
    });
    $(".country-dropdown-3").bind("change", function(){

        if(changeL){
            $("#LicenseeAddressForm_state").remove();
            $("#state-option-wrap-3").append(originalLicenseeStateDropdown);
        }

        if($(this).val() != 'US'){
            $("#LicenseeAddressForm_state").remove();
            $("#state-option-wrap-3").append('<input type="text" id="LicenseeAddressForm_state" name="LicenseeAddressForm[state]" class="text-input" />');                
            changeL = true;
        }else{
            changeL = false;
        }
    });
    if($("#BillingAddressForm_country")){
        if($("#BillingAddressForm_country").val() == ''){
            $("#BillingAddressForm_country").val('US');
        }
    }
    if($("#ShippingAddressForm_country")){
        if($("#ShippingAddressForm_country").val() == ''){
            $("#ShippingAddressForm_country").val('US');
        }
    }
    /*
         * Validate Email / Form
         */
    $(".validate-email").bind("blur", function(){
        var p = validateEmail($(this).attr("id"),$(this).val());
        if(!p){
            $(this).next(".error").empty().append("The Email Address is Not Valid!").fadeIn("fast");
            $(this).addClass("error");
        }
        if(p){
            $(this).next(".error").hide();
            $(this).removeClass("error");
            $(".username").val($(this).val());
        }
    });
    $(".v-form").click(function(){
        var val = true;
        $(".validate-email").each(function(){
            var p = validateEmail($(this).attr("id"),$(this).val());
            if(!p){
                $(this).next(".error").empty().append("The Email Address is Not Valid!").fadeIn("fast");
                $(this).addClass("error");
                val = false;
            }
            if(p){
                $(this).next(".error").hide();
                $(this).removeClass("error");
                $(".username").val($(this).val());
            }
        });
        if(val){
            $("form").submit();
        }
    });
    /*
         * Update Input
         */
    $(".update-you").bind("keyup", function(){
        var v = $(this).val(); 
        var h = $(this).attr("data-aj");
        $("#"+h).val(v);
    });
    /*
         * Toggle Anything
         */
    $(".toggle-you").click(function(){
        toggleYou(this);
    });
    $(".toggle-you-checkbox").change(function(){
        toggleYou(this);
    });
    if($(".toggle-you-checkbox").attr("checked")=='checked'){
        toggleYou($(".toggle-you-checkbox"));
    }
    /*
         * Restyle for Return False Clicks
         */
    $(".return-false").click(function(){
        return false;
    });
    $("input[name='shipping_method_id']").bind("change", function(){
        $(".content-section-overlay").fadeTo("fast", 0.6);
        $("#shipping_method").submit();
    });
    /* Ajax Login from any page */
    $("#login_ajax, .login_ajax").bind({
        click: function(){
            ajaxLogin();
        },
        dblclick: function(){
            ajaxLogin();
        }
    });
    $("#login_ajax_forum").bind({
        click: function(){
            ajaxLogin();
            return false;
        },
        dblclick: function(){
            ajaxLogin();
            return false;
        }
    });
    $(".close-overlay").live("click", function(){
        closeOverlay();
    });
    $(".close").live("click", function(){
        closeOverlay();        
    });
    function closeOverlay(){
        $(".wrapper-content-section-overlay").fadeOut();
        $(".wrapper-content-section-overlay-data").fadeOut();
        $(".wrapper-content-section-overlay-data").empty();
        $("body").css("overflow", "auto");
    }
    /* Z-Index iFrame Fix */
    $(".vendor_description").find("iframe").each(function(){
        var src = $(this).attr("src");
        src = src+'?wmode=Opaque';
        //console.log(src);
        $(this).attr("src", src);
    });
    fixSidebar();
    /* Double Click Return False */
    $(".dbclick-check").bind({
        click: function(){
            //$(this).parent("div").find(".overlay").fadeTo("fast", 0.6);
            $(".wrapper-content-section-overlay").fadeTo("fast", 0.5);
            $(".wrapper-content-section-overlay").css("height", $(document).height()+"px");
            $(".wrapper-content-section-overlay-loading-data").show();
            window.location.hash = 'header';
            $("#wrapper").css("height", $(".wrapper-content-section-overlay").height()+"px");
            $("#wrapper").css("overflow", "hidden");
            watchHash();
        },
        dblclick: function(){
            //$(this).parent("div").find(".overlay").fadeTo("fast", 0.6);
            $(".wrapper-content-section-overlay").fadeTo("fast", 0.5);
            $(".wrapper-content-section-overlay").css("height", $(document).height()+"px");
            $(".wrapper-content-section-overlay-loading-data").show();
            window.location.hash = 'header';
            $("body").css("height", $(".wrapper-content-section-overlay").height()+"px");
            $("body").css("overflow", "hidden");
            watchHash();
        }
    });
    checkHash();
    /* POP Up */
    $(".popup-holder").find(".jsdisplay").live("click", function(){
        $.ajax({
            url:$(this).attr("href"),
            success: function(data){
                loadModal(data, 'product');                   
            }
        });
        window.location.hash='#top';
        return false;
    });
}); // END DOM READY
function watchHash(){
    var id = intervalTrigger();
}
function intervalTrigger() {
  return window.setInterval( function() {
    if(window.location.hash !='#header'){
        window.location.hash = '#header';
    }
  }, 300 );
};
function fixSidebar(){
    var s = $("#sidebar").height();
    var ads = $(".ad-box").height();
    if(ads){
        $("#sidebar").height((s+ads)+'px');
    }

    if($(".blog-content").length > 0){
        var blogHeight = 0;
        $(".sidebar").each(function(){
           blogHeight = blogHeight + $(this).height();
        });
        $(".blog-content").css("min-height", blogHeight+"px");
    }
}

function getTwitter(){
    $.get('/inc/social/getTwitter.php', function(data){
        $.each(data, function(i, item) {
            $("#load-twitter").replaceWith(data);
        });
    });
}
function ajaxLogin(){
    var url = window.location.href;
    url = url.replace("http://www.toolfarm.com", "");
    url = url.replace("http://dev.toolfarm.com", "");
    $.ajax({
        url:'/ajax/login/&return='+url,
        type: 'GET',
        success: function(data){
            loadModal(data);
        }
    });
}
function toggleCustomerType() {

    var newCustomerAction = '/sso/register/';
    var returningCustomerAction = $(".login-page form").attr("action");
    redirect = 0;

    $(".login-page form").attr("action", newCustomerAction);

    if($("#customer-type-returning").attr("checked")!='checked'){
        $("#password").fadeTo("fast", 0.4);
        $("#password").attr("readonly", "readonly");
    }   

    $("#customer-type-new").attr("checked", "checked");
    $("#customer-type-returning").attr("checked", false);

    $(".customer-type").bind("change", function(){
        if($(this).val()==0){
            $("#password").attr("readonly", "readonly");
            $("#password").fadeTo("fast", 0.4);
            $("#password").val("");
            $(".login-page form").attr("action", newCustomerAction);
            redirect = 0;
            $(".update-cart").css("display", "none");
            $("#redirect-link").css("display", "block");
        }else{
            $("#password").attr("readonly", false);
            $("#password").fadeTo("fast", 1);
            $(".login-page form").attr("action", returningCustomerAction);
            redirect = 1;
            $(".update-cart").css("display", "block");
            $("#redirect-link").css("display", "none");
        }
    });
    $("#redirect-link").click(function(){
        $("#redirect-link").attr("href", "/sso/register/&e="+$("#name").val());
    });
    $("#name").bind("keyup", function(){
        $("#redirect-link").attr("href", "/sso/register/&e="+$("#name").val());
    });
    $(".update-cart").css("cursor", "pointer");
}
function checkTabs(){
    if($("#show_upgrades_tab").val() == 0){
        $("#upgrades_tab").hide();            
    }
    if($("#show_renders_tab").val() == 0){
        $("#renders_tab").hide();
    }
    if($("#show_renders_tab").val() == 0 && $("#show_upgrades_tab").val() == 0){
        $("#new_tab").hide();
    }
}
function checkRelatedItems(){
    if($("#related_item_list li").length == 0){
        $("#related_item_header").hide();
    }
}
function toggleYou(t){
    $("#"+$(t).attr("ref")).slideToggle();
}
function validateEmail(form_id,email) {
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    if(reg.test(email) == false) {
        return false;
    }else{
        return true;
    }
}
function returnSize() {
    var data = new Array();
    var myWidth = 0, myHeight = 0;
    if( typeof( window.innerWidth ) == 'number' ) {
        //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }
    data['width'] = myWidth;
    data['height'] = myHeight;

    return data;
}

function loadDemo() {
    $(".load-demo").bind("click", function(){
        var id = $(this).attr("id");
        var _this = this;
        if($("#load-" + id).is(":visible")){
            $("#load-" + id).slideToggle("slow");
            $(_this).addClass("closed");
            $(_this).removeClass("open");
        }else{
            if($(_this).hasClass("active")){
                $("#load-" + id).slideToggle("slow", function(){
                    $(_this).addClass("open");
                    $(_this).removeClass("closed");
                });                
            }else{
                $(_this).removeClass("open"); 
                $(_this).addClass("loading"); 
                $("#overlay-" + id).fadeTo("fast", 0.6);
                $.ajax({
                    url: '/demo_download_hostapp/' + $(this).attr("id"),
                    success: function(data){
                        $("#load-" + id).append(data).slideToggle("slow", function(){
                            $(_this).removeClass("loading");
                            $(_this).addClass("active");
                            $(_this).addClass("open");
                            $(_this).removeClass("closed");
                            $("#overlay-" + id).fadeTo("slow", 0.0);
                            $("#overlay-" + id).hide();
                        });                       
                    }
                });               
            }
        }
    });
}

function checkBoxes(t){
    if($(t).hasClass("selected")){
        $(t).removeClass("selected");
        $(t).find("input:checkbox").removeAttr("checked");
    }else{
        $(t).addClass("selected");
        $(t).find("input:checkbox").attr("checked", "checked");
    }   
    updateSelected(t);
}

function selectLi(t){
    if($(t).parent("li").hasClass("selected")){
        $(t).parent("li").removeClass("selected");
    }else{
        $(t).parent("li").addClass("selected");
    }   
    updateSelected(t);
}

function updateSelected(t){
    var num = 0;
    if($(t).parent().find(":checkbox").length > 0){
        num = $(t).parent().parent().parent().find(":checked").length;
        $(t).parent().parent().parent().find(".selected-demos").empty().append(num);
    }else if($(t).parent().parent().find(":checkbox").length > 0){
        num = $(t).parent().parent().find(":checked").length;
        $(t).parent().parent().parent().find(".selected-demos").empty().append(num);
    }else{
    //Do Nothing???
    }
    updateMasterSelected();
}

function checkAllDemos(t){
    $(t).parent(".select-options").parent("div").find(":checkbox").each(function(){
        $(this).attr("checked", "checked");
        $(this).parent("li").addClass("selected");
    });
    updateSelected(t);
}

function uncheckAllDemos(t){
    $(t).parent(".select-options").parent("div").find(":checkbox").each(function(){
        $(this).attr("checked", false); 
        $(this).parent("li").removeClass("selected");
    });
    updateSelected(t);
}

function updateMasterSelected(){
    var n = $(":checked").length;
    $("#total-selected-demos").find("span").empty().append(n);
}

function checkHash(){
    if(window.location.hash) {
        if(window.location.hash=='#upgrade'){
            removeTabClasses();
            $("#upgrades_tab").parent("li").addClass("ui-tabs-selected").addClass("ui-state-active");
            var tab = $("#upgrades_tab").attr("href");
            $(tab).removeClass("ui-tabs-hide").addClass("ui-tabs-selected").addClass("ui-state-active");
        }else if(window.location.hash=='#render'){
            removeTabClasses();
            $("#renders_tab").parent("li").addClass("ui-tabs-selected").addClass("ui-state-active");
            var tab = $("#renders_tab").attr("href");
            $(tab).removeClass("ui-tabs-hide").addClass("ui-tabs-selected").addClass("ui-state-active");            
        }
    }
}
function removeTabClasses(){
    $("#tab-set").find("li").each(function(){
        $(this).removeClass("ui-tabs-selected").removeClass("ui-state-active");
    });
    $(".box-tab").each(function(){
        $(this).addClass("ui-tabs-hide");
    });
}

function loadModal(data, type){
    if(type == null){
        type = 'login';
    }
    var st = document.body.scrollTop;// + (document.body.clientHeight *  document.body.clientWidth);
    var size = returnSize();
    var p = getScrollingPosition();
    $("body").css("height", size['height']);
    $("body").css("overflow", "hidden");
    $(".wrapper-content-section-overlay-"+type+"-data").append(data);
    var h = $(".wrapper-content-section-overlay-"+type+"-data").height();
    h = (size['height'] / 2) - (h + 20);
    var w = $(".wrapper-content-section-overlay-"+type+"-data").width();
    w = (size['width'] / 2) - w;
    if(type=='product'){
        w = w - 300;
    }
    $(".wrapper-content-section-overlay-"+type+"-data").css("margin-left", w);
    $(".wrapper-content-section-overlay-"+type+"-data").css("margin-top", (h+p.Top));
    $(".wrapper-content-section-overlay").css("height", size['height']).css("margin-top", p.Top+"px");
    $(".wrapper-content-section-overlay").css("width", size['width']);
    $(".wrapper-content-section-overlay").fadeTo("fast", 0.8);
    $(".wrapper-content-section-overlay-"+type+"-data").fadeIn("fast");

}

function getScrollingPosition()
{
    position=new Object();
    if (typeof window.pageYOffset != 'undefined')
    {
        position.Top = window.pageYOffset;
        position.Left = window.pageXOffset;
    }
    else if (typeof document.documentElement.scrollTop
        != 'undefined' && document.documentElement.scrollTop > 0)
        {
        position.Top = document.documentElement.scrollTop;
        position.Left = document.documentElement.scrollLeft;
    }
    else if (typeof document.body.scrollTop != 'undefined')
    {
        position.Top = document.body.scrollTop;
        position.Left = document.body.scrollLeft;
    }
    return position;
}

