//
//  First load the js specific css then set stuff up all purdy-like
//
//setCSS('has-js');
var menuTimer = "";
var hideTimer = "";
$(document).ready(function () {
    preLoadImages();
    livenMenu();
    if ($(".ticker").length > 0) {
        enableTicker();
    }
});

var enableTicker = function() {
    var ticker = $(".ticker");
    ticker.data("paused", false);
    $(".ticker a").hover(function() {
                             ticker.data("paused", true);
                         },
                         function() {
                             ticker.data("paused", false);
                         });
    setInterval(function() {
        if (!ticker.data("paused")) {
            var current = $(".ticker a:visible").slideUp(300);
            var next = current.next("a");
            setTimeout(function() {
                (next.length > 0 ? next : $(".ticker a:first")).slideDown(300);
            }, 300);
        }
    }, 5000);

};

function livenMenu() {

    $("#side-nav-menu").hover(function() {},
                              function() {
                                  $("#side-nav-menu div.element-cont").each(function() {
                                      if(!$(this).children("a").hasClass("sub-selected") && !$(this).hasClass("selected")) {
                                          $(this).children("span").css("background-position", "0px 0px");
                                          $(this).children(".sub-menu").slideUp(300);
                                      }
                                  });
                              });
    $("#side-nav-menu div.element-cont").each(function() {
       if($(this).children("div").length > 0 && $(this).children("div").css("display") == "none") {
           $(this).append('<span class="arrow"></span>');
       }

       $(this).hover(function(e) {
                         clearTimeout(menuTimer);
                         if($(this).children("div").length > 0 && $(this).children("div").css("display") == "none") {
                             var obj = this;
                             menuTimer = setTimeout(this.hoverState = function() {
                                 $(obj).children("span").css("background-position", "0px -10px");
                                 $(obj).children(".sub-menu").slideDown(300);
                             }, 250);
                         }
                      },
                      function() {});
    });
}

function clearField(el) {
    if ($(el).val() == "Email Address") {
        $(el).css({ color: "#444444" }).val("");
    }
}

function resetField(el) {
    if ($(el).val() == "") {
        $(el).css({ color: "#C9C9C9" }).val("Email Address");
    }
}

function animateContent() {
	$("#content-inner").css("display", "none");
	$("#content-inner").fadeIn(1000);
}

function preLoadImages() {
    image_url = new Array();
    image_url[0] = "/sites/all/themes/appatureinc/images/logo.png";
    image_url[2] = "/sites/all/themes/appatureinc/images/loader_bar.gif";

    i0 = new Image();
    i0.src = image_url[0];
    i2 = new Image();
    i2.src = image_url[2];

}

function setCSS(cssName) {
    var css = document.createElement("link");
    css.setAttribute("href",'/sites/all/themes/appatureinc/' + cssName + '.css');
    css.setAttribute("rel","stylesheet");
    css.setAttribute("type","text/css");
    document.getElementsByTagName("head")[0].appendChild(css);
}

function checkForm(pageId, element) {
    $.scrollTo(0, 300, {easing:'easeInOutQuad'});
    id = $(element).attr("id");
    //
    // Validate the form by contacting the backend
    //
    $("#" + id).attr("action", "/validate");
    $.prompt('<div class="ajax-sending"><img src="/sites/all/themes/appatureinc/images/loader_bar.gif" alt="loader"></div>', {show:'fadeIn', overlayspeed: "fast", promptspeed: "fast", opacity: 0.7, buttons: { Close: true}, submit: function() { highlightEmptyRequired(id); removeResume(id); return true; } });

    $("#" + id).ajaxSubmit(function(data) {
        if (!data.substring(0,24).match('error')) {
            //
            // Give success response
            //
            var response = document.createElement("div");
            $(response).attr({id: "form-response"});
            $(response).html(data);

            $("#content-area").css({overflow: "hidden", width: "822px", position: "relative"});
            $("#content").css({overflow: "hidden", position: "relative"});
            setTimeout(function() { $("#content-area").html(response);
                                    $("#content-area").css("height", "700px");
                                    $("#content-area").show(100);
                                    $("#jqifade").remove();
                                    setTimeout(function() { $("#form-response").animate({left: "0px"}, { duration: 500, easing: "easeInOutQuad" }); }, 300);
                                    setTimeout(function() { $("#jqibox").hide(300); setTimeout(function() {
                                        $("#jqibox").remove();
                                        if (pageId == "campaign") {
                                            $("#content").css({ overflow: "visible" });
                                            $("#content-inner").css({ width: "900px" });
                                            $("#content-area").css({ width: "900px", height: "auto" });
                                        }
                                    }, 250); }, 250); }, 300);
        } else {
            $("div.jqimessage").html(data);
            $("div.jqi .jqibuttons").css("display", "block");
        }
    });


    return false;
}

function checkNewDemoForm(pageId, element) {
    $.scrollTo(0, 300, {easing:'easeInOutQuad'});
    id = $(element).attr("id");
    //
    // Validate the form by contacting the backend
    //
    $("#" + id).attr("action", "/validate");
    $.prompt('<div class="ajax-sending"><img src="/sites/all/themes/appatureinc/images/loader_bar.gif" alt="loader"></div>', {show:'fadeIn', overlayspeed: "fast", promptspeed: "fast", opacity: 0.7, buttons: { Close: true}, submit: function() { highlightEmptyRequired(id); return true; } });

    $("#" + id).ajaxSubmit(function(data) {
        if (!data.substring(0,24).match('error')) {
                $("#jqibox").remove();

		$("#demo-form-div").hide();		
		setCookie("appatureDemoContact","videos");
		$("#demo-content").show();
		ytplayer.loadVideoById(demoSrcLink.substring(1));
        } else {
            $("div.jqimessage").html(data);
            $("div.jqi .jqibuttons").css("display", "block");
        }
    });


    return false;
}

function checkNewResourcesForm(pageId, element) {
    $.scrollTo(0, 300, {easing:'easeInOutQuad'});
    id = $(element).attr("id");
    //
    // Validate the form by contacting the backend
    //
    $("#" + id).attr("action", "/validate");
    $.prompt('<div class="ajax-sending"><img src="/sites/all/themes/appatureinc/images/loader_bar.gif" alt="loader"></div>', {show:'fadeIn', overlayspeed: "fast", promptspeed: "fast", opacity: 0.7, buttons: { Close: true}, submit: function() { highlightEmptyRequired(id); return true; } });

    $("#" + id).ajaxSubmit(function(data) {
        if (!data.substring(0,24).match('error')) {
                $("#jqibox").remove();

		setCookie("appatureWorkbookContact","resources");
		window.location = resourceSrcLink;
        } else {
            $("div.jqimessage").html(data);
            $("div.jqi .jqibuttons").css("display", "block");
        }
    });


    return false;
}

function ie6ImageChanges() {
    if ($.browser.msie && $.browser.version == "6.0") {
        if($("#content").height() > 750) {
            $("#content").css("background", "#FFFFFF");
        }
    }
}

function highlightEmptyRequired(id) {
  $("#" + id + " input.required").css("background-image", "url('/sites/all/themes/appatureinc/images/input_bg_required.gif')");

  $("#error-message li").each(function() {
      var elementId = $(this).attr("name");
      $("#" + id + "-" + elementId).css("background-image", "url('/sites/all/themes/appatureinc/images/input_bg_error.gif')");
      $("#" + id + "-" + elementId).focus(function() {
                                              $(this).css("background-image", "url('/sites/all/themes/appatureinc/images/input_bg_required.gif')");
                                         });
  });

}

function removeResume(id) {
    if ($("#" + id + "-resume").length > 0) {
        if ($("#careers-form-resume").val().length > 0) {
            $("#" + id + "-resume").parents("div:first").append("<span id=\"upload-message\"><b>Resume Stored.</b> (<a href=\"#\" id=\"re-upload\">Use Different Resume</a>)<input type=\"hidden\" name=\"resume_stored\" value=\"y\"></span>");
            $("#" + id + "-resume").next("label").css("display", "none");
            var resume = $("#" + id + "-resume");
            $("#" + id + "-resume").remove();

            $("#re-upload").click(function() {
                     $("#" + id + "-resume").next("label").css("display", "inline");
                     $("#re-upload").parents("div:first").append(resume);
                     $("#upload-message").remove();
                     return false;
                }
            );
        }
    }
}

var addEmail = function() {
    var length = $(".email-addresses input[type=text]").length;
    $(".email-addresses .more").before('<input style="color: #444" id="email' + length + '" type="text" maxlength="200" name="email' + length + '" value="" onblur="resetField(this)" onfocus="clearField(this)"/>');
    setTimeout(function() { $(".email-addresses input[type=text]:last").focus(); }, 50);
}


function flashVideoFinished() {
    $(".campaign-video-finished").slideDown();
    $.post("/validate", { "type" : "video" }, function(data) {
    }, "json");
}

function forwardToFriend() {
    var emails = {};
    var emailCount = 0;
    emails.type = "forward";
    $(".email-addresses input").each(function() {
        var content = $(this).val();
        if (content.indexOf("@") != -1) {
            emailCount++;
            emails[$(this).attr("id")] = content;
        }
    });

    if (emailCount > 0) {
        $(".campaign-toolbar h2 img").show();
        $.post("/validate", emails, function(data) {
            $(".email-addresses").html(data.message);
            $(".campaign-toolbar h2 img").hide();
        }, "json");
    } else {
        alert("Please enter at least 1 email address.");
    }
}
