//
// - - - - - - - - - - - - - - -
// - - - - - - DEBUG - - - - - -
// - - - - - - - - - - - - - - -
//
var _debug_enabled = false;
jQuery.noConflict();
function initDebug(){
    var tmp_fb = console;
    tmp_fb.msg = function(msg, params){

        typeof(params) != 'undefined' ? console.log("[[[ Excel ]]]: " + msg + params.toString()) : console.log("[[[ Excel ]]]: " + msg);

    }

    return tmp_fb;
}
var fb = _debug_enabled && typeof(console) != 'undefined' ? initDebug() : {
    log         : function(){},
    debug       : function(){},
    info        : function(){},
    warn        : function(){},
    error       : function(){},
    assert      : function(){},
    dir         : function(){},
    dirxml      : function(){},
    trace       : function(){},
    group       : function(){},
    groupEnd    : function(){},
    time        : function(){},
    timeEnd     : function(){},
    profile     : function(){},
    profileEnd  : function(){},
    count       : function(){},
    msg         : function(){}
};


// Excel namespace
// Excel project's functionality
//
Excel = {
    callbacks	: {},
    functions	: {},
    listeners   : {},
    objs        : {},
    classes     : {},
    utils	: {},
    vars	: {},
    events  : {}
};

//
// - - - - - - - - - - - - - - - - -
// - - - - - - VARIABLES - - - - - -
// - - - - - - - - - - - - - - - - -
//


// Js Scripts repository
//
Excel.vars.jsSrc = "/img/js/";
Excel.vars.scriptLoaded = false;
Excel.vars.loadGoogleMapTimeout = 50;

//
// - - - - - - - - - - - - - - - - -
// - - - - - - FUNCTIONS - - - - - -
// - - - - - - - - - - - - - - - - -
//

Excel.functions.identify = function(){
    fb.msg("Generating new ID");
    var v_id = "anonymous_" + Math.floor(Math.round(Math.random()*193150));
    var v_id_seek = "#"+v_id;
    fb.msg("Generated ID: "+v_id);
    if(jQuery(v_id_seek).length > 0){
        fb.msg("[Regenerating id] Duplicate found for ID: "+v_id);
        return Excel.functions.identify();
    }else{
        return v_id;
    }
    //return v_id;
};

//
// Raiting tabs
//
Excel.functions.raitingTabs = function(){
    function change_tab(tab){
        jQuery(".tabbed-content > ol").addClass("hidden");
        if(!jQuery(tab).hasClass("selected"))
        {
            jQuery(".selected").removeClass("selected");

            jQuery(tab).addClass("selected");


        }
        if(jQuery(tab).is(":first-child")){
            jQuery("#top-universities").removeClass("hidden");
        }else{
            jQuery("#top-countries").removeClass("hidden");
        }
    }

    jQuery(".tabbed-links > li").bind("click",function(evt){
        evt.preventDefault();
        change_tab(this);
    });

}



//
// Dynamic script loading
//
Excel.functions.loadScript = function(scriptName, callback){

    fb.msg("Loading external JS file: ", scriptName);

    var head = jQuery("head");
    var script= document.createElement('script');

    jQuery(script).attr("type", "text/javascript")
    jQuery(script).attr("src", Excel.vars.jsSrc + scriptName);
    jQuery(head).append(script);

    if('undefined' != typeof(callback) && null != callback){
        script.onreadystatechange = function () {
            if (this.readyState == 'complete' || this.readyState == 'loaded') callback();
        };
        script.onload = callback();
    }

    fb.msg("Script loaded successfully: ", scriptName);
};
//
// Check if dynamicaly loading script finished downloading
//
Excel.functions.isScriptLoaded = function(){
    if(Excel.vars.scriptLoaded === true){
        // flush scriptLoaded var
        //
        Excel.vars.scriptLoaded = false;

        return true;
    }else{
        return false;
    }
}
//
// Video player loader
//
Excel.functions.addVideo = function(src, settings){
    var configs = {
        width       : 400,
        height      : 300,
        img         : null,
        container   : "videoObject",
        flashId     : null,
        callback    : null,
        playerSrc   : "/img/flv_player/player.swf",
        skin        : null
    };
    fb.msg("Video Settings: ", settings);
    typeof(settings) != 'undefined' ? jQuery.extend(configs, settings) : false;

    configs.flashId != null ? configs.flashId : configs.flashId = Math.floor((Math.random()*10000));

    if(typeof(SWFObject) == 'undefined'){

        Excel.functions.loadScript("swfobject.js", Excel.callbacks.setScriptLoaded);
        while(Excel.functions.isScriptLoaded() === false){
            //
        }
    }

    var so = new SWFObject(configs.playerSrc, "flashmovie_" + configs.flashId, configs.width, configs.height, "6.0.0");
    so.addParam("wmode", "transparent");
    so.addParam('allowscriptaccess','always');
    so.addParam('allowfullscreen','true');
    null != configs.callback ? so.addParam("callback",configs.callback) : false;
    so.addVariable("file", src);
    fb.msg("SWFObject: ", so);
    null != configs.skin ? so.addVariable("skin", configs.skin) : false;
    null != configs.img ? so.addVariable("image", configs.img) : false;
    null != configs.callback ? so.addVariable("callback", configs.callback) : false;
    jQuery(document).ready(function(){
        so.write(configs.container);
    });
    fb.log("Container: " + configs.container);

};

Excel.functions.showCentered = function(element){
    jQuery(element).hide();
    jQuery(element).css("position","absolute");
    jQuery("body").append(element);

    Excel.functions.reCenter(element);
};

Excel.functions.reCenter = function(element){
    var viewDimensions = {
        width: jQuery(window).width(),
        height: jQuery(window).height()
    }
    objectDimensions = {
        width: jQuery(element).width(),
        height:  jQuery(element).height()
    }


    jQuery(element).css("left", (viewDimensions.width/2) - (objectDimensions.height/2));
    jQuery(element).css("top", jQuery(document).scrollTop() + (viewDimensions.height/2)-(objectDimensions.height/2));

    jQuery(element).show();
};

Excel.functions.trackPositioned = function(){
    jQuery(window).scroll(function(){
        jQuery(Excel.vars["trackingElements"]).each(function(ind, element){
            var offset = Excel.vars[jQuery(element).attr("id")] + jQuery(document).scrollTop();

            jQuery(element).animate({
                top:offset
            },{
                duration:500,
                queue:false
            });

        });

    });

};


//
// Simple Comments-form validation
//
Excel.functions.validateComments = function(){
    jQuery(document).ready(function(){
        jQuery("#add-comment-form :submit").bind("click",function(evt){
            evt.preventDefault()

            var isValid = true;
            var form = jQuery("#add-comment-form");
            jQuery(form).find("h3").addClass("hidden");

            if(jQuery(form).find("input[name=name]").val().match("^(\ )*$")){
                jQuery("#error-name").removeClass("hidden");
                isValid = false;
            }
            if(!RegExp("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}").test(jQuery(form).find("input[name=email]").val())){
                jQuery("#error-mail").removeClass("hidden");
                isValid = false;
            }
            if(jQuery(form).find("textarea[name=message]").val().match("^(\ )*$")){
                jQuery("#error-message").removeClass("hidden");
                isValid = false;
            }

            isValid ? jQuery(form).submit() : false;
        });
    });

}



//
// Subscribe manips
//
Excel.functions.subscribeForm = {};
Excel.functions.subscribeForm.hintInputs = function(){
    jQuery(document).ready(function(){

        jQuery("#username:not([type=hidden])").bind("focus blur", function(evt){
            jQuery(this).removeClass("bordered_error");
            if(evt.type == 'focus' && jQuery(this).val() == '??????'){
                jQuery(this).val("");

            }

            if(evt.type == 'blur' && jQuery(this).val().length == 0){
                jQuery(this).val("??????");
            }

        });
        jQuery("#user-email:not([type=hidden])").bind("focus blur", function(evt){
            jQuery(this).removeClass("bordered_error");
            if(evt.type == 'focus' && jQuery(this).val() == 'e-mail'){
                jQuery(this).val("");

            }

            if(evt.type == 'blur' && jQuery(this).val().length == 0){
                jQuery(this).val("e-mail");
            }

        });

        jQuery("#submit-subscription-request").bind("click", function(evt){
            var valid = true;

            var userName = jQuery("#username");
            var userEmail = jQuery("#user-email");



            if(jQuery(userName).val() == '??????' || (jQuery(userName).val().search("^(\ )*$") == 0)){
                valid = false;
                jQuery(userName).addClass("bordered_error");

            }
            if(jQuery(userEmail).val() == 'e-mail' || (new RegExp("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}").test(jQuery(userEmail).val()) == false)){
                valid = false;
                jQuery(userEmail).addClass("bordered_error");
            }

            valid ? true : evt.preventDefault();

        });

    });



}

//
// Order tabs
//
Excel.functions.order_tabs = function(){

	// inline func set
	//

        // making tab block visible
        jQuery('#order-form').removeClass('hidden');

	// show Thank-you and submit forms
	function thanks_and_submit_brochure(){
		jQuery("#body_order_brochure").addClass("hidden");
		jQuery(".thank-you").removeClass("hidden");

        setTimeout("jQuery('.thank-you').addClass('hidden');",4000);

        var fields = {};
        jQuery("#order-project > fieldset input[type!=hidden]").each(function(i, o){
            fields[jQuery(o).attr("id")] = jQuery(o).val();
        });
        jQuery.post("/form-order-brochure/?action=send",fields);

	}

	function thanks_and_submit_program(){
		jQuery("#body_order_programe").addClass("hidden");
		jQuery(".thank-you").removeClass("hidden");

        setTimeout("jQuery('.thank-you').addClass('hidden');",4000);

        var fields = {};
        jQuery("#order-project-programe > fieldset input[type!=hidden]").each(function(i, o){
            fields[jQuery(o).attr("id")] = jQuery(o).val();
        });
        jQuery.post("/form-order-program/?action=send",fields);

	}



	// check if form is valid
	function is_form_valid(form){
		jQuery("#order-form").find(".bordered_error").removeClass("bordered_error");
		var valid = true;

		jQuery(".order-tabs .bordered_error")

		var fields = form + "  > fieldset > input";
            	jQuery(fields).each(function(index, field){
			if(jQuery(field).attr("name") == "mail"){
				if(new RegExp("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}").test(jQuery(field).val()) == false){
					valid = false;
					jQuery(field).addClass("bordered_error");
				}
			}else{
				if(jQuery(field).val().search("^(\ )*$") == 0){
					valid = false;
					jQuery(field).addClass("bordered_error");
				}
			}
		});


            	return valid;

	}

	function open_brochure(evt){
		evt.preventDefault();
		jQuery("#order-form .selected-item").removeClass("selected-item");

		// insert default values
		if(jQuery("#order-project input#programm").val() == ""){
			jQuery("#order-project input#programm").val(jQuery("#content-column > .entry-title").text());
		}

		jQuery("#body_order_programe").addClass("hidden");
		jQuery("#body_order_brochure").toggleClass("hidden");

		jQuery("#body_order_brochure").css("display") != 'none' ? jQuery(this).parent().addClass("selected-item") : false;
	}

	function open_program(evt){
		evt.preventDefault();
		jQuery("#order-form .selected-item").removeClass("selected-item");

		// insert default values
		if(jQuery("#order-project-programe input#program").val() == ""){
			jQuery("#order-project-programe input#program").val(jQuery("#content-column > .entry-title").text());
		}
		if(jQuery("#order-project-programe input#country").val() == ""){
			jQuery("#order-project-programe input#country").val(jQuery("#leading-headname > .entry-title").text());
		}


		jQuery("#body_order_brochure").addClass("hidden");
		jQuery("#body_order_programe").toggleClass("hidden");

		jQuery("#body_order_programe").css("display") != 'none' ? jQuery(this).parent().addClass("selected-item") : false;
	}

	jQuery(document).ready(function(){
		jQuery("#order_brochure a").bind("click", open_brochure);
		jQuery("#order_program a").bind("click", open_program);

        jQuery("#order-form").bind("submit", function(evt){
            evt.preventDefault();

            if(!jQuery("#body_order_brochure").hasClass("hidden")){
                is_form_valid("#order-project") ? thanks_and_submit_brochure() : false;
            }else{
                is_form_valid("#order-project-programe") ? thanks_and_submit_program() : false;
            }
        });


	});

}





//
// - - - - - - - - - - - - - - - - -
// - - - - - - CALLBACKS - - - - - -
// - - - - - - - - - - - - - - - - -
//

//
// Script downlownloading checker
//
Excel.callbacks.setScriptLoaded = function(){
    Excel.vars.scriptLoaded = true;
};


Excel.callbacks.openVideoWindow = function(evt){
    evt.preventDefault();
    var gid = Math.floor((Math.random()*1500));


    fb.msg("Start");
    if(typeof(jQuery(this).data("videobox_id")) != 'string'){
           var videobox = jQuery("#templates").find(".videobox").clone();
	var UID = Excel.functions.identify();
        Excel.objs.videoWindows[UID] = new Excel.classes.VideoWindow(videobox);
        jQuery(videobox).attr("id", UID);
        var videoObject_uid = Excel.functions.identify();
	jQuery(this).data("videobox_id", "#" + UID);

        fb.log(videoObject_uid);

        jQuery(videobox).find(".videoObject").attr("id",videoObject_uid);
        jQuery(videobox).prependTo("body");

        var video2load = jQuery(this).attr("href");
                fb.msg("Loading video: ", video2load);
                var imgSrc = jQuery(this).find("img").attr("src");
                Excel.functions.addVideo(video2load,{
                    img: jQuery(this).css("background-image").replace(/url\(/,"").replace(/\)/,""),
                    width: 440,
                    height: 320,
                    skin: "/img/skin/modieus.swf",
                    container: videoObject_uid
                });

                // TITLE
                var title = jQuery(this).parent('.hentry').find('.entry-title > a').text();
                Excel.objs.videoWindows[UID].manager( title || '-' );

                Excel.functions.showCentered(videobox);
                Excel.vars[jQuery(videobox).attr("id")] = jQuery(videobox).offset().top - jQuery(window).scrollTop();
                Excel.vars["trackingElements"].push(videobox);



                jQuery(videobox).show();
                return false;
        }else{
            jQuery(jQuery(this).data("videobox_id")).show();

            return false;
        }


};



//
// - - - - - - - - - - - - - - - -
// - - - - - - CLASSES - - - - - -
// - - - - - - - - - - - - - - - -
//

//
// World clocks at date toolbar
//
Excel.classes.Clock = function(){
    var settingsForLondon = {
        utc : true,
        utc_offset : 0
    };

    var settingsForNY = {
        utc : true,
        utc_offset : -3
    };

    var settingsForSydney = {
        utc : true,
        utc_offset : +11
    };

    this.main = function(){
        fb.msg("Starting timers");

        jQuery("#london > span").jclock(settingsForLondon);
        jQuery("#ny > span").jclock(settingsForNY);
        jQuery("#sydney > span").jclock(settingsForSydney);

        fb.msg("Timers started");
    }

    this.start = function(){

        Excel.vars.jsReady = Excel.functions.loadScript("jquery.clock.js", this.main);

    }

};

Excel.classes.VideoWindow = function(videoBoxUID){
    var self = this;
    this.player = null;
    this.videoBox = videoBoxUID;
    //
    // Truncate title text if it is too long.
    //
    this.truncateLongTitles = function( title ){
        
        return title.length > 55 ? ( title.substr(0, 55) + "...") : title;
    },
    this.manager = function( title ){
        title = this.truncateLongTitles( title );
        
        var titleHolder = jQuery(this.videoBox).find(".top-title");//.text();
        jQuery(titleHolder).text( title );

        //
        // z-positioning
        //
        jQuery(this.videoBox).css("z-index",100);
        while('undefined' == jQuery(this.bindedElement).find("embed").attr("id")){
        //
        }

        // If draggables not loaded
        //
        if('undefined' == typeof(jQuery.ui)){
            Excel.functions.loadScript("ui.core.js", Excel.callbacks.setScriptLoaded);
            while(Excel.functions.isScriptLoaded() === false){
            //
            }
            Excel.functions.loadScript("ui.draggable.js", Excel.callbacks.setScriptLoaded);
            while(Excel.functions.isScriptLoaded() === false){
        //
        }

        }

        this.mover = jQuery(this.videoBox).next(".videobar");
        var opts = {
            handle: this.mover,
            opacity: '0.75',
            stop: function(event, ui){
                Excel.vars[jQuery(self.videoBox).attr("id")] = jQuery(self.videoBox).offset().top - jQuery(window).scrollTop();
            }
        };
        jQuery(this.videoBox).draggable(opts);
        //
        // Toggles z-position
        //
        jQuery(this.videoBox).bind("click", function(){
            jQuery(".videobox").css("z-index", 50);
            jQuery(self.videoBox).css("z-index", 100);
        });

        //
        // Control buttons
        //
        // Minimize, Maximize
        //
        jQuery(this.videoBox).find(".minimize-button").bind("click", function(evt){
            evt.preventDefault();

            fb.log(jQuery(self.videoBox).find(".videoContainer"));
            fb.log(jQuery(self.videoBox).find(".videoContainer").css("opacity"));
            if(jQuery(self.videoBox).find(".videoContainer").css("opacity") == 0)
            {
                jQuery(self.videoBox).find(".corner-bottom-left2, .corner-bottom-right2").hide();
                jQuery(self.videoBox).find(".grad-bottom2").css("padding-bottom", "0px");
                jQuery(self.videoBox).find("embed").show();
                jQuery(self.videoBox).find(".videoContainer").animate({
                    opacity: 1
                }, "slow", null, function(){
                   //

                });

                jQuery(self.videoBox).find(".phantom, .phandom2").show();

            }
            else
            {
                jQuery(self.videoBox).find("embed").hide();

                jQuery(self.videoBox).find(".phantom, .phandom2").hide();

                jQuery(self.videoBox).find(".videoContainer").animate({
                    opacity: 0
                }, "slow", null, function(){
                    jQuery(self.videoBox).find(".corner-bottom-left2, .corner-bottom-right2").show();
                    jQuery(self.videoBox).find(".grad-bottom2").css("padding-bottom", "6px");
                });

                 jQuery(self.videoBox).find(".phantom, .phandom2").hide();
            }
        });


        // Phantom: Click => Play / Stop
        jQuery(self.videoBox).find(".phantom, .phandom2").bind("click", function(evt){
            evt.preventDefault();

            var flash_embed = jQuery(evt.target).parent(".video-wrapper").find("embed").attr("id");
            fb.log(evt);
            fb.log(flash_embed);
            var state = document.getElementById(flash_embed).getConfig().state;
            state == 'PLAYING' || state == 'BUFFERING'
                ? document.getElementById(flash_embed).sendEvent("PLAY", "false")
                : document.getElementById(flash_embed).sendEvent("PLAY", "true");

        });

        // Close window
        //
        jQuery(self.videoBox).find(".close-button").bind("click",function(evt){
            evt.preventDefault();

            jQuery(self.videoBox).hide();
        });


        //if( jQuery.browser.msie )
        jQuery(self.videoBox).find('.minimize-button').addClass('hidden');
    },

    this.listenersLoaded = function(){

    },


    function calculateLoading(obj){
        if(jQuery(this.videoBox).find(".loading").css("display") == "none")
        {
            jQuery(this.videoBox).find(".loading").show();
        }


        var loaded = obj.loaded * 100 / obj.total;

        if(loaded > 100){
            loaded = 100;
        }
        //jQuery("#loaded").text(Math.floor(loaded) +"%");
        // if downloaded and is hided, hightlight
        if(loaded == 100)
        {
            jQuery(this.videoBox).find(".loading").hide();
            jQuery(this.videoBox).find(".loaded").show();

            if(jQuery(this.videoBox).find(".videocontainer").css("opacity") == 0)
            {
                var videoBar = jQuery(this.videoBox).find(".videobar");
                jQuery(videoBar).fadeOut(150);
                jQuery(videoBar).fadeIn(150);
                jQuery(videoBar).fadeOut(150);
                jQuery(videoBar).fadeIn(150);

            }
        }
    },

    this.main = function(){


    },

    this.start = function(){
        this.main();
    }
};

Excel.classes.Tabs = function(){
    var self = this;
    this.changeTab = function(tab){
        if(!jQuery(tab).hasClass("active"))
        {

            jQuery(".active").removeClass("active");
            var currentTabId = jQuery(tab).find(".tab_header").attr("id").split("tab-header-")[1];
            jQuery(".tab_body").hide();
            jQuery("#tab_body_" + currentTabId).fadeIn("normal");
            jQuery(tab).addClass("active");
        }
    },
    this.main = function(){
        jQuery("#tabs").hide();
        var tabs = jQuery("#tabs > ul").get();
        var bodies = jQuery("#tabs > .tab_body");
        jQuery(tabs).each(function(index, header){

            jQuery("#tabs_headers").append(header);

        });

        jQuery(bodies).each(function(index, body){

            jQuery("#tabs_bodies").append(body);

        });

        jQuery("#tabs_headers .tabs-name:first").addClass("active");
        jQuery("#tabs_bodies > .tab_body:not(:first)").hide();

        jQuery("#tabs_placeholder").show();



        jQuery(".tabs-name").bind("click", function(){
            self.changeTab(this);

        });

        Excel.functions.loadScript("jquery.lightbox-0.5.js");
        jQuery(".lightbox").length != 0 ? jQuery(".lightbox").lightBox({fixedNavigation: true}) : false;
    },
    this.start = function(){
        jQuery("#tabs").ready(function(){
            self.main();
        });
    }
};

//
// - - - - - - - - - - - - - - -
// - - - - - - UTILS - - - - - -
// - - - - - - - - - - - - - - -
//

Excel.utils.clock = {};
Excel.utils.clock.init = function(){

    jQuery(document).ready(function(){
        Excel.objs.clock = new Excel.classes.Clock();
        Excel.objs.clock.start();
    });

};

Excel.utils.videoWindow = {};
Excel.utils.videoWindow.init = function(){

    jQuery(document).ready(function(){
        //
        // Init the video windows
        //
        Excel.objs.videoWindows = new Array();
        Excel.vars["trackingElements"] = new Array();
        /*var UID = null;
        try{
            jQuery(".videobox").each(Excel.callbacks.openVideoWindow);
        }catch(e){
            fb.log(e);
        }
      */
     jQuery(".video_source").bind("click", Excel.callbacks.openVideoWindow);

    });

    Excel.functions.trackPositioned();


};
Excel.utils.tabs = {};
Excel.utils.tabs.init = function(){
    jQuery(document).ready(function(){
        Excel.objs.tabs = new Excel.classes.Tabs();
        Excel.objs.tabs.start();

    });
};

//
// - - - - - - - - - - - - - - - -
// - - - - - - Dom:load - - - - - -
// - - - - - - - - - - - - - - - -
//
jQuery(document).ready(function(){
    typeof(jQuery(".tabs-wrapper")) != 'undefined' ? Excel.functions.raitingTabs() : false;
    Excel.utils.videoWindow.init();


    /*var icon_randomizer = Math.floor(Math.random()*10);
    icon_randomizer != 9 ? icon_randomizer *= 21 : icon_randomizer = 0;
    icon_randomizer = "0 -" + icon_randomizer + "px";
    jQuery(".poll-results").css("background-position", icon_randomizer);
    */

});
