// Tambi Jalouqa - Binary interactive

// globals
// ishra7 sound
var mySound;
var firstVideo = true;
var contactFormOpen = false;
var currentHoveredButton = "";

$(document).ready(function() {

    if ($.browser.webkit) {
        $.browser.safari = ( $.browser.safari && /chrome/.test(navigator.userAgent.toLowerCase()) ) ? false : true;
    } else {
        $.browser.safari = false;
    }

    $("#gettingStartedSection").css('display', 'none');
    $(".highlighter").css('display', 'block');

    soundManager.url = './swf';
    soundManager.debugFlash = false;

    soundManager.onready(function() {

        // SM2 has loaded - now you can create and play sounds!
        mySound = soundManager.createSound({
            id: 'aSound',
            url: '/mp3/ishra7.mp3'
            // onload: [ event handler function object ],
            // other options here..
        });
    });

    // make the thumbList a scrollable list
    if($('.thumbList').length > 0)
        $('.thumbList').tinyscrollbar();

    $("#slideShowNavigation ul li a").live('click', function(e) {
        showSlideshowHover(this);
        e.preventDefault();
    });

    $(".about, .why, .process").click(function() {
        var targetSectionId = $("a", this).attr('rel');
        changeSection(targetSectionId);
        highlight(this);
    });

    $(".overview ul li a").click(function(e) {
         $("#selectedVideo").attr("id", "");
            $(this).parent().attr("id", "selectedVideo");
            var targetVideoId = $(this).attr('rel');
            $("#videoTitle").html($(this).attr('title'));
            $("#videoDescription").html($("div", $(this).parent()).html());
        
        if (swfobject.hasFlashPlayerVersion("9.0.0")) {


            loadPlayerYoutube(targetVideoId);
            e.preventDefault();
        } else {
            //return true;
        }
    });

    $("#playSoundClipBtn").click(function(e) {
        mySound.play();
        e.preventDefault();
    });

    $("#getStartedBtn").click(function(e) {
        $("#gettingStartedSection").slideDown('slow');
        $("#thankYou").css('display', 'none');
        e.preventDefault();
    });

    $(".contact").click(function(e) {
        showContactOverlay();
        e.preventDefault();
    });

    $("#formCloseBtn").live('click', function(e) {
        closeContactForm();
        e.preventDefault();
    });

    $("#cancelBlock a").click(function(e) {
        $("#gettingStartedSection").slideUp('slow');
        e.preventDefault();
    });

    $('#greatExplanation').jqEasyCounter({
        'maxChars': 140,
        'maxCharsWarning': 130,
        'msgFontSize': '12px',
        'msgFontColor': '#645031',
        'msgFontFamily': 'Arial',
        'msgTextAlign': 'right',
        'msgWarningColor': '#CC0000',
        'msgAppendMethod': 'insertAfter'
    });

    //initialize the first menu item
    //load the first video

    $(".thumbList ul li a:first").click();
    if (swfobject.hasFlashPlayerVersion("9.0.0")) {
        // flash enabled
    } else {
        $("#videoComponent").html("<img src='./img/header/altVideo.png' style='float:right' />");
    }

    $(window).bind('resize', onResize);

    $.address.change(function(event) {
        switch (event.value) {
            case "/contact":
                // show contact info
                showContactOverlay();
                break;
            case "/what":
                $(".about").click();
                break;
            case "/why":
                $(".why").click();
                break;
            case "/process":
                $(".process").click();
                break;
            case "/":
                $(".about").click();
                break;
        }
    });

    $("#subscribeForm").validate({
        submitHandler: function() {
            onSubscribeFormDone();
            return false;
        }});

        preloadImages();

});

/*****************************************
 *  add the overlay and the contact us form
 *****************************************/
function showContactOverlay() {
    if (!contactFormOpen) {
        if (!$("#contactForm").length > 0) {
            $("<div id='contactForm'>" + $("#contactFormBody").html() + "</div>").appendTo("body");
            $("#contactFormBody").remove();
        }
        $("#contactForm input, #contactForm textarea").val('');
        $("#contactFormField div").css('display', 'none');
        $("#contactButton").attr("disabled", false);
        $("#contactForm form").validate({
            submitHandler: function() {
                onContactFormDone();
                return false;
            }});
        $("#contactForm").css('left', $("#slideShowContent").offset().left - 7).css('top', $("#slideShowContent").offset().top - 6).css('display', 'none').fadeIn('fast');
        contactFormOpen = true;
    }
}

/*****************************************
 * Close the contact form
 *****************************************/
function closeContactForm() {
    if (contactFormOpen) {
        contactFormOpen = false;
        $("#contactForm").fadeOut('fast', function() {
//            $(this).remove();
        });
    }
}

/*****************************************
 * Change the section state
 ******************************************/
function changeSection(targetSectionId) {
    var targetIndex = -1;
    for (var i = 0; i < slideShowData.length; i++) {
        if (slideShowData[i].section == targetSectionId) {
            targetIndex = i;
            break;
        }
    }

    $("#slideShowContent").empty();
    $("#slideShowNavigation ul").empty();

    for (var j = 0; j < slideShowData[targetIndex].slides.length; j++) {
        $("#slideShowContent").append(' <div class="singleSlide" id="slide' + ( j + 1 ) + '">' + slideShowData[targetIndex].slides[j] + '</div>');
        $("#slideShowNavigation ul").append('<li><a href="" rel="slide' + ( j + 1 ) + '"><h2>' + slideShowData[targetIndex].buttons[j] + '</h2></a></li>');
    }

    $("#slideShowNavigation ul li a:first").click();

    closeContactForm();
}

/*****************************************
 * Handle the success of submitting the subscribe form
 *****************************************/
function onSubscribeFormDone() {
    var formElement = $("#subscribeForm");
    $("#susbscribeButton").attr("disabled", true);
    $.post(formElement.attr('action'), { name: $("#nameInput").val(), company: $("#companyInput").val() , email : $("#emailInput").val(), brief : $("#greatExplanation").val()},
            function(data) {
                $("#subscribeForm input, #subscribeForm textarea").val('');
                $("#susbscribeButton").attr("disabled", false);
                $("#thankYou").fadeIn();
            });
}

/*****************************************
 * Handle the success of submitting the contact form
 *****************************************/
function onContactFormDone() {
    var formElement = $("#contactFormElements");
    $("#contactButton").attr("disabled", true);
    $.post(formElement.attr('action'), { name: $("#contactNameInput").val(), company: $("#contactCompanyInput").val() , email : $("#contactEmailInput").val(), brief : $("#contactBriefInput").val()},
            function(data) {
                $("#contactForm input, #contactForm textarea").val('');
                $("#contactButton").attr("disabled", false);
                $("#contactFormField div").fadeIn();
            });
}

function highlight(target) {
    $("#mainNav li a.selected").removeClass("selected");

    var targetLink = $("a", target);
    $(targetLink).addClass("selected");

    //$("#highlighter").css('left',$(targetLink).position().left - $("#highlighter").parent().position().left + $(targetLink).width() * .5 - 10 );

    // disabled while developing because its annoying
     $(".highlighter").animate({ left:$(targetLink).position().left + ($(targetLink).width()*.5) - 480 },
                500);
}

// adds the hovered button to the body tag and sets the text from the h2 of the target sent
function showSlideshowHover(target) {

    var targetSlideId = $(target).attr('rel');
    currentHoveredButton = target;

    $(".currentSlide").css('z-index', '100');
    $("#" + targetSlideId).css('z-index', '101').fadeIn('normal', function() {
        $(".currentSlide").css('display', 'none').css('position', 'absolute').removeClass("currentSlide");
        $(this).addClass('currentSlide');
    });

    $("#slideShowHoverButton").remove();
    $("body").append("<div id='slideShowHoverButton'><h2>" + $("h2", target).html() + "</h2></div>");
    $("#slideShowHoverButton").css('left', $(target).parent().offset().left - 26).css('top', $(target).parent().offset().top);
}

function onResize() {
    $("#slideShowHoverButton").css('left', $(currentHoveredButton).parent().offset().left - 26).css('top', $(currentHoveredButton).parent().offset().top);
}


//// Player functions
function loadPlayerYoutube(videoID) {
    if (document.getElementById("ytPlayer")) {
        document.getElementById("ytPlayer").loadVideoById(videoID);
    } else {

        clearOldVideo();
        // Lets Flash from another domain call JavaScript
        var params = { allowScriptAccess: "always" , wmode: "opaque"};
        // The element id of the Flash embed
        var atts = { id: "ytPlayer"  };
        // All of the magic handled by SWFObject (http://code.google.com/p/swfobject/)
        var autoPlay = '';
        if (firstVideo) {
            firstVideo = false;
        } else {
            autoPlay = "&autoplay=1";
        }
        swfobject.embedSWF("http://www.youtube.com/v/" + videoID + "&enablejsapi=1&playerapiid=player1&showinfo=0" + autoPlay, "videoDiv", "480", "295", "8", null, null, params, atts);
    }
}

function clearOldVideo() {
    var element = $("#videoComponent");
    element.empty().append('<div id="videoDiv"></div>');
}

function preloadImages(){
    for (var i = 0; i < slideShowData.length; i++) {
        for (var j = 0; j < slideShowData[i].slides.length; j++) {
            $(slideShowData[i].slides[j]);
        }
    }
}

