var WIDTH = 980;
var CT=0;
var CTH=0;
var bgpath = '/images/right_bgs/';
var top_bgpath = '/images/right_bgs_top/';
var IElt6 = ($.browser.msie && $.browser.version<="6.0") ? true : false;
var IE7 = (navigator.appVersion.indexOf("MSIE 7.")==-1) ? false : true;
var IE8 = (navigator.appVersion.indexOf("MSIE 8.")==-1) ? false : true;
var IE9 = (navigator.appVersion.indexOf("MSIE 9.")==-1) ? false : true;
var firefox3 = ( $.browser.mozilla == true && $.browser.version < '3.8' ) ? true : false;
// For use within normal web clients
var isiPad = navigator.userAgent.match(/iPad/i) != null;
// For use within iPad developer UIWebView
var ua = navigator.userAgent;
isiPad = /iPad/i.test(ua) || /iPhone OS 3_1_2/i.test(ua) || /iPhone OS 3_2_2/i.test(ua);
var isiPhone = navigator.userAgent.match(/iPhone/i) != null;
var isMAC = navigator.userAgent.match(/mac/i) != null;
var ajaxFunctionsSrc = "/inc.ajax.main.content.php";
var ajaxTopMenuSrc = "/inc.toparea.php";
var ajaxBlogSrc = "/inc.blog_container.php";
var ajaxAwardsSrc = "/inc.awards_container.php";
var ajaxProjectMenuSrc = "/inc.projectmenu.php";
var display_message="";
var smallSlideShow;
var TopAreaHeight = 1033;
var startUrl;
var link;
var zone = 1;
var timer;
var currentProjectSelected =1;
var airFlag=200;

$(document).ready(function() {
    var lang=$('a.lang-selected').text().toLowerCase();
    if(lang!="gr"){
        ajaxTopMenuSrc = "/inc.toparea_"+lang+".php";
    }
    var DEFAULT_PAGE_OPEN = $("#default_open_page").html();
    docWidth();
    if(!isiPad && !isiPhone){
        menuSelect();
    }
    initHeaderBanners();
    initCSS();
    photoSlide();
    topΜenuSelect();
    checkForms();
    TopAreaSlider();
    registerNewsletter();
    $(window).resize(function() {
        docWidth();
    });
    $.history.init(function(url){
        if(url == "") {
            // initialize your app
            if(location.href.split("/").pop()=="" || location.href.split("/").pop()=="index.php"){//if home
                currentMenuOpen("/"+DEFAULT_PAGE_OPEN);
            }
            if(location.href.split("/").pop()=="aliens"){currentMenuOpen("/"+DEFAULT_PAGE_OPEN);$('#top_links_left a').trigger("click");}
        } else {
            // restore the state from hash
            runHistory(url);
        }
    },
    {unescape: ",/;=?&"}
    );
});

function initHeaderBanners(){
    $('body').append('<div class="imagePreloaderHeader"><img onload="drawHeaderBanner()" src="/images/banner1_down.png" /><img onload="drawHeaderBanner()" src="/images/banner1_up.png" /><img onload="drawHeaderBanner()" src="/images/banner2_down.png" /><img onload="drawHeaderBanner()" src="/images/banner2_up.png" /></div>');
}

function drawHeaderBanner(){
    CTH++;
    if(CTH==4){
        $('#header_banners').fadeIn(600);
        headerOpen();
        if(!isiPad && !isiPhone){
            $("#header_open").trigger("click");
        }
        banner2Hover();
        $('.imagePreloaderHeader').remove();
    }
}

//RUN HISTORY
function runHistory(url){
    //var pid = url.split("?")[1]; //get current subpage
    var pid = url.split("/")[1]; //get current subpage
    var params;
    //url = url.split("?")[0];
    url = url.split("/")[0];
    var l=$('a.lang-selected').text().toLowerCase();

    if(location.href.indexOf('php')>0){
        startUrl=location.href;
    }
    if(location.href.indexOf("#")==-1){
        link = location.pathname;
    }
    url=url==""?startUrl:url;
    
    if(pid){
        pid = pid.replace(/pid=/gi, "");
        params = 'q='+encodeURI(url)+'&pid='+pid;
    }
    else{
        params = 'q='+encodeURI(url);
    }
    if(zone=="1"){ //default
        currentMenuOpen("/"+url);
        ajax_call(ajaxFunctionsSrc,params,'ajaxCallback');
    }
    else if(zone=="2"){ajax_call(ajaxProjectMenuSrc,params,'rightSubMenuCallback');}//project
    else if(zone=="3"){ajax_call(ajaxBlogSrc,params,'blogCallback');}//blog
    else if(zone=="4"){ajax_call(ajaxAwardsSrc,params,'blogCallback');}//awards
}

//find body width
function docWidth(){
    if($(window).width()<WIDTH){
        $('body').css("overflow-x", "scroll");
    }
    else{
        $('body').css("overflow-x", "hidden");
        $(window).scrollLeft(0);
    }
}

//find left container bg top and set it
function leftBGset(){
    if(($("#main_header").height()+$("#main_content").height())>$("#right_image_load img").height()){
        if(($("#second_content").find(".photo_slide").length==0) && (($(".people_container").length==0)) && ($('.client_area').length==0)){
                var leftBGtop = ($("#right_image_load").height() - $('#main_header').height());
                var leftBGheight = ($("#main_content").height() - leftBGtop);
                $("#main_content").prepend('<div class="backSkewDiv skewDiv"></div>');
                $(".backSkewDiv").css({"top":leftBGtop+"px","height":leftBGheight+"px"});
        }
    }       
}

//blog link selection
function postBlogSelect(){
    $(".articleItems a,.postItems a,a.blogTitleLink,.blogMore a").click(function(){
        zone = 3;
        var cur_category = $(this).attr("href").split("/")[1];
        var cur_pid = $(this).attr("href").split("/")[2];
        //historyCall($(this).attr("href"),null);
        historyCall(cur_category,cur_pid);
        return false;
    });
}

//awards link selection
function postAwardsSelect(){
    $(".articleItems a,.postItems a,a.blogTitleLink").click(function(){
        zone = 4;
        var cur_category = $(this).attr("href").split("/")[1];
        var cur_pid = $(this).attr("href").split("/")[2];
        historyCall(cur_category,cur_pid);
        return false;
    });
}

//main menu select
function menuSelect(){
    $("#main_menu_container .main_menu li a,.right_menu li a").click(function(){
        menuClickSelection($(this),true);
        return false;
    });
}

function miniMenuSelect(){
    $(".mini_menu li a").click(function(){
        menuClickSelection($(this),false);
        return false;
    });
}

function menuClickSelection(target,$mainmenu){
    if($("#top_header_area_container").hasClass("opened")){
        closeTopSlider();
        $(window).scrollTop(0);
    }
    if($mainmenu){
        $("#main_menu_container .main_menu li a,.right_menu li a").removeClass("selected");
    }
    else{
        $(".mini_menu li a").removeClass("selected");
    }
    target.addClass("selected");
    zone = 1;
    historyCall(target.attr("href"),null);
}

//current menu select (for history)
function currentMenuOpen(h){
    var l=$('a.lang-selected').text().toLowerCase();
    h='/'+l+h;
    $("#main_menu_container .main_menu li a,.right_menu li a").removeClass('selected');
    $('#main_menu_container .main_menu li a[href="'+h+'"],.right_menu li a[href="'+h+'"]').addClass("selected");
    getBottomHeader();
}

//main menu select
function topΜenuSelect(){
    $("#top_menu_container .top_main_menu li a").click(function(){
        $("#top_menu_container .top_main_menu li a").removeClass("selected");
        $(this).addClass("selected");
        topMenuCall($(this).attr("href"));
        return false;
    });
}

//initialize css
function initCSS(){
    $('#top_links_left').stop(true,true).animate({'top':'-61px'},2000);
    if(IElt6){
        $("#left_wrapper").html('<div class="divContainer" ><img src="/images/small_tria_logo.jpg" alt="TRIA" /><br/></div><div class="divContainer"><span class="warning">Please update your browser...</span></div>');
    }
    if(IE8){
        $('body').css("overflow", "auto");
    }
    if(location.href.indexOf("#")==-1){
        animateContent();
        var current_bg = $("#bg_image_set").html();
        if(isiPad || isiPhone){
            $("#right_image_load").html('<img alt="" src="'+bgpath+current_bg+'" />');
        }
        else{
            $('#right_image_load').stop(true,false).fadeOut(0);
            initBGimage(current_bg);
        }
        
    }
    peopleInfo();
    $('#slideshow_content :first-child').fadeIn();

    //no css3 browsers-run animation with javascript
    if(isiPad || isiPhone || firefox3){
        photoSlideHover();
    }
    runSmallGallery();
}

function getBottomHeader(){
    var mainMlength = $("#main_menu_container ul.main_menu li a.selected").length;
    if(mainMlength>0){
        if(!$('#drawClientSlide').is(':visible')){
            $("#drawNewsletter").fadeOut(800);
            $("#drawClientSlide").fadeIn(800);
        }
    }
    else{
        if(!$('#drawNewsletter').is(':visible')){
            $("#drawClientSlide").fadeOut(800);
        $("#drawNewsletter").fadeIn(800);
        }
    }
}

//loadVideoContent
function loadVideoContent(video_url){
    jwplayer("mediaplayer").setup({
            flashplayer: "/scripts/player.swf",
            file: video_url,
            controlbar: 'bottom',
            width: 315,
            height: 190
    });
}

//loadVideo
function loadVideo(){
    $(".loadVideo a").click(function(){
       loadVideoContent($(this).attr("href"));
       return false;
    });
}

//call ajax general function
function ajax_call(url, params, callback){
    var l=$('a.lang-selected').text().toLowerCase();
    $.ajax({
            type: "GET",
            url: url,
            cache: false,
            data: params+"&l="+l,
            beforeSend:function() {
                    //$('.loader').fadeIn(180);
            },
            success: function(result){
                    //$('.loader').fadeOut(180);
                if(callback!=''){
                    eval(callback + "(result)");
                }
            }
    });
}

//main content animation
function animateContent(){
    $("#main_content").stop(true,true).slideUp(0).slideDown(1250,function(){
        if($("#slide-menu").length>0){
            miniMenuClick();
        }
        if(location.href.split("/").pop()!="" && location.href.split("/").pop()!="index.php"){
            documentSlideDown();
        }
        //drawImagesFix();
        loadSocial();
    });
}

//need for IE 7
function parseURL(h,pid,zone){
    h = h.split("/");
    if(pid){
        //$.history.load(h[h.length-1]+'?pid='+pid);
        $.history.load(h[h.length-1]+'/'+pid);
    }
    else{
        $.history.load(h[h.length-1]);
    }
}

//call the history function
function historyCall(h,pid){
    h = h.split("/").pop();
    if ((!IE7)){
        if(pid){
            //$.history.load(h+'?pid='+pid);
            $.history.load(h+'/'+pid);
        }
        else{
            $.history.load(h);
        }
    }
    else {
        parseURL(h,pid);
    }
}

//call the history function
function topMenuCall(h){
    h = h.split("/").pop();
    if ((!IE7)){
        ajax_call(ajaxTopMenuSrc,'top='+h,'ajaxTopMenuCallback');
    }
    else {
        parseURL(h,null);
    }
}

function rightBGcounter(image){
    CT++;
    if(CT==1){
        $("#right_image_load").html('<img alt="" src="'+bgpath+image+'" />').fadeIn(520,function(){
            leftBGset();
        });
        $('.imagePreloader').remove();
    }
}

function initBGimage(image){
    CT=0;
    $('body').append('<div class="imagePreloader"><img onload="rightBGcounter(\''+image+'\');" src="'+bgpath+image+'"></div>');
}

function rightBGcounterTOP(image){
    CT++;
    if(CT==1){
        $('#right_ufo_image').children(".right_ufo").html('<img alt="" src="'+top_bgpath+image+'" />').fadeIn(520,function(){
            leftBGset();
        });
        $('.imagePreloader').remove();
    }
}

function initBGimageTOP(image){
    CT=0;
    $('body').append('<div class="imagePreloader"><img onload="rightBGcounterTOP(\''+image+'\');" src="'+top_bgpath+image+'"></div>');
}

function ajaxCallback(data){
    $("#main_content").html(data);
    var current_bg = $("#bg_image_set").html();
    if(current_bg == ""){
        current_bg = "digital.jpg";
    }
    animateContent();
    photoSlide();
    $("#right_image_load").fadeOut(300,function(){
        if(isiPad || isiPhone){
            $("#right_image_load").html('<img alt="" src="'+bgpath+current_bg+'" />').fadeIn(500);
        }
        else{
            initBGimage(current_bg);
        }
    });
    $('#right_ufo_image').children(".right_ufo").fadeOut(300);
    peopleInfo();
    //$("head").children("title").html("Tria ::. "+$("#page_title").html());
    document.title = "Tria ::. "+$("#page_title").html();
}

function blogCallback(data){
    $('html,body').stop(true,true).animate({scrollTop: $("#main_content").position().top - 40+"px"},400);
    $(".containerLeft").children(".blog_area").stop(true,true).fadeOut(400,function(){
        $(".backSkewDiv").remove();
        $(".containerLeft").children(".blog_area").html(data).fadeIn(500,function(){
            leftBGset();
            loadSocial();
        });
    });
}

function loadSocial() {
    //I will assume that if we have one type of button we have them all
    //If not we'll just exit
    if ($(".twitter-share-button").length == 0){
        return;
    }
    else{
        $.getScript('http://platform.twitter.com/widgets.js', function(){
            //calling method load
            twttr.widgets.load();
        });
    }

    //Facebook
    if (typeof (FB) != 'undefined') {
        FB.init({ status: true, cookie: true, xfbml: true });
    } else {
        $.getScript("http://connect.facebook.net/en_US/all.js#xfbml=1", function () {
            FB.init({ status: true, cookie: true, xfbml: true });
        });
    }

    //Linked-in
    if (typeof (IN) != 'undefined') {
        IN.parse();
    } else {
        $.getScript("http://platform.linkedin.com/in.js");
    }

    //Google - Note that the google button will not show if you are opening the page from disk - it needs to be http(s)
    if (typeof (gapi) != 'undefined') {
        $(".g-plusone").each(function () {
            gapi.plusone.render($(this).get(0));
        });
    } else {
        $.getScript('https://apis.google.com/js/plusone.js');
    }
}

function ajaxTopMenuCallback(data){
    $('#right_ufo_image').children(".right_ufo").fadeOut(800);
    $("#top_header_area_load").stop(true,true).fadeOut(0).html(data).stop(true,true).fadeIn(700,function(){
        var current_top_bg = $("#top_bg_image_set").html();
        if(current_top_bg == ""){
            current_top_bg = "1.jpg";
        }
        $('#right_image_load').fadeOut(0);
        if(isiPad || isiPhone){
            $('#right_ufo_image').children(".right_ufo").html('<img alt="" src="'+top_bgpath+current_top_bg+'" />').fadeIn(450);
        }
        else{
            initBGimageTOP(current_top_bg);
        }
    });
}

//needed for non css3 browsers
function photoSlideHover(){
    
    $(".photo_slide li a,.people_item_image a").hover(
        function() {
            $(this).parent().css({'z-index' : '5'}); /*Add a higher z-index value so this image stays on top*/
            $(this).children('img').addClass("hover").stop() /* Add class of "hover", then stop animation queue buildup*/
                .animate({
                        top: '-45px',
                        left: '-44px',
                        width: '300px', /* Set new width */
                        height: '304px' /* Set new height */
                }, 210); /* this value of "200" is the speed of how fast/slow this hover animates */
        } , function() {
            $(this).children('img').stop()  /* Remove the "hover" class , then stop animation queue buildup*/
                .animate({
                        top: '0',
                        left: '0',
                        width: '212px', /* Set width back to default */
                        height: '215px' /* Set height back to default */
                }, 200,function(){
                    $(this).removeClass("hover");
                    $(this).parent("a").parent().css({'z-index' : '2'}); /* Set z-index back to 2 */
                });
        }
    );
}

function photoSlide(){
    $(".photo_slide li a").click(function(){
        zone = 1;
        $(".main_menu li a,.right_menu li a").removeClass("selected");
        $('.right_menu li a[href="/people.php"]').addClass("selected");
        historyCall("/people",$(this).attr("id"));
        return false;
    });

    if(isiPad || isiPhone || IE7 || IE8 || IE9 || firefox3){
        photoSlideHover();
    }
}

function peopleInfo(){
     
    var cur_person = $("#current_people_selected").html();
   
    $(".people_item .cross_icon").click(function(){
       if($(this).parent(".people_item_container").parent(".people_item").hasClass("opened")){
           closePerson($(this).parent(".people_item_container").parent(".people_item"));
       }
       else{
           $('.people_item.opened').children(".people_item_container").children(".cross_icon").trigger("click");
            closePerson($('.people_item[id='+cur_person+'].opened'));
            openPerson($(this).parent(".people_item_container").parent(".people_item"));
       }
    });
    $(".people_item_image a").click(function(){
        $(this).parent(".people_item_image").parent(".people_item").children(".people_item_container").children(".cross_icon").trigger("click");
        return false;
    });
    if(cur_person!="" && cur_person!=null ){
        openPerson($('.people_item[people_url='+cur_person+']'));
    }
}

function openPerson(target){
    target.addClass("opened").children(".people_item_container").children(".people_item_info").stop(true,true).slideDown(800);
    target.children(".people_item_container").children(".cross_icon").css({'background-position':' -24px 0'});
}

function closePerson(target){
    target.removeClass("opened").children(".people_item_container").children(".people_item_info").stop(true,true).slideUp(400);
    target.children(".people_item_container").children(".cross_icon").css({'background-position':' 0 0'});
}

/*form checks*/
function checkForms(){
    $('input,textarea').live('focusin',function(){
        if($(this).val()==$('#hidden_'+$(this).attr('name')).val()){
            $(this).val('');
        }
    });
    $('input,textarea').live('focusout',function(){
        if($(this).val()==""){
            $(this).val($('#hidden_'+$(this).attr('name')).val());
        }
    });
}

/*fields check */
function CheckValidMail(email,name){
    if(email!=""){
        var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/;
        if(emailPattern.test(email)){
            $('input[name="'+name+'"]').css('border','1px solid #DEDEDE');
            return true;
        }
        else{
            $('input[name="'+name+'"]').css('border','1px solid #ff0000');
            display_message+='<div>'+$('#error_hidden_valid_email').val()+'</div>';
            return false;
        }
    }
    else{
        return false;
    }
    
}
function CheckInputNotNull(element,element_name){
    if(element!="" && element!="undefined" && element!="Το όνομά σας" && element!="Το e-mail σας"){
        $('input[name='+element_name+']').css('border','1px solid #DEDEDE');
        return true;
    }
    else{
        $('input[name='+element_name+']').css('border','1px solid #ff0000');
        display_message+='<div>'+$('#error_hidden_'+element_name).val()+'</div>';
        return false;
    }
}

function ClearSmallForm(){
    $('.form_item input,.form_item textarea').each(function(){
        $(this).val($('#hidden_'+$(this).attr("name")).val()).css('border','1px solid #DEDEDE');
    });
}

function ClearForm(){
    $('.formItem input,.formItem textarea').val('');
}


/* REGISTERS */

function registerContact(){
    $('.message').empty().slideUp(300);
    var passed = true;
    display_message = "";
    var name = $('#contact_name').val();
    var surname = $('#contact_surname').val();
    var email = $('#contact_email').val();
    var occasion = $('#contact_occasion').val();
    var comments = $('#contact_comments').val();

    if(!CheckInputNotNull(name,"name"))
        passed = false;
     if(!CheckInputNotNull(surname,"surname"))
        passed = false;
    if(!CheckInputNotNull(email,"email"))
        passed = false;
    if(!CheckValidMail(email,"email"))
        passed = false;
    //send form
        if(passed){
            display_message = "<div>Sending...</div>";
            $('.message').html(display_message).fadeIn(600);
            $.post('/send.contact.php' , {name:name,surname:surname,email:email, occasion:occasion, comments:comments}, function(data) {
                $('.message').html(data).fadeIn(600);
                ClearForm();
            });
        }
        else{
            $('.message').html(display_message).stop(true,true).slideDown(800);
        }
}

function registerNewsletter(){
    $("a#sendMail").click(function(){
       $('.newsletter_message').empty().stop(true,true).fadeOut(0);
       var passed = true;
       display_message = "";
       var email = $('#newsletter_input').val();
       var lang=$('a.lang-selected').text().toLowerCase();
       if(!CheckInputNotNull(email,"newsletterEmail")) passed = false;
       if(!CheckValidMail(email,"newsletterEmail")) passed = false;
       if(passed){
           display_message = "<div>Sending...</div>";
           $('.newsletter_message').html(display_message).fadeIn(600);
           $.post('/ajax.newsletter_response.php' , {email:email, lang:lang}, function(data) {
                $('.newsletter_message').html(data).fadeIn(600);
                $('#newsletter_input').val("");
            });
       }
       else{
           $('.newsletter_message').html(display_message).fadeIn(600,function(){
               $(this).delay(8000).queue(function(){
                  $('.newsletter_message div').fadeOut(600,function(){$('.newsletter_message').empty();});
                  $('#newsletter_input').css('border','1px solid #DEDEDE');
               });
           });
       }
        
       return false;
    });
}

function registerJob(){
    $('.job_message').empty().slideUp(300);
    var passed = true;
    display_message = "";
    var name = $('#job_name').val();
    var email = $('#job_email').val();
    var comments = $('#job_comments').val();

    if(!CheckInputNotNull(name,"name"))
        passed = false;
    if(!CheckInputNotNull(email,"email"))
        passed = false;
    if(!CheckInputNotNull(comments,"comments"))
        passed = false;
    if(!CheckValidMail(email,"email"))
        passed = false;
    //send form
        if(passed){
            display_message = "<div>Sending...</div>";
            $('.job_message').html(display_message).fadeIn(600);
            $.post('/send.job.contact.php' , {name:name,email:email, comments:comments}, function(data) {
                $('.job_message').html(data).fadeIn(600);
                ClearSmallForm();
            });
        }
        else{
            $('.job_message').html(display_message).stop(true,true).slideDown(800);
        }
}

/*Small Slide Show Gallery*/

var currentIndexSmall = 0;

function runSmallGallery(){
    clearInterval(smallSlideShow);
    smallSlideShow = setInterval( "smallGallery()", 4000 );
}

function smallGallery(){
        var totalImagesSmall = $('.small-main-gallery-image-slider img').length;

        if(currentIndexSmall < totalImagesSmall-1){
            currentIndexSmall++;
        } else {
            currentIndexSmall = 0;
        }
        moveSliderSmall(currentIndexSmall);
}

function moveSliderSmall(currentIndexSmallGallery){
    $('.small-main-gallery-image-slider').stop(true,true).animate({marginLeft:-(166*currentIndexSmallGallery)},600);
}

//function howToWinSlider
function TopAreaSlider(){
    if(isiPad || isiPhone){
        $('#top_links_left a,#top_menu_close a').mousedown(function(){
            if($("#top_header_area_container").hasClass("opened")){
                closeTopSlider();
            }
            else{
                openTopSlider();
            }
            return false;
        });
    }
    else{
        $('#top_links_left a,#top_menu_close a').click(function(){
            if($("#top_header_area_container").hasClass("opened")){
                closeTopSlider();
            }
            else{
                openTopSlider();
            }
            return false;
        });
    }
}
function openTopSlider(){
    $('#top_header_area_container').addClass("opened").stop(true,true).animate({height:TopAreaHeight+"px"},1950,function(){
        $('#top_links_left').stop(true,true).animate({'top':'-61px'},300);
    });
    $('#top_links_left').stop(true,true).animate({'top':'61px'},500);
    $('#top_menu').stop(true,true).fadeIn(1600);
    $('#right_image_load').stop(true,true).fadeOut(900,function(){
        $('#right_ufo_image').children(".right_ufo").stop(true,true).fadeIn(900);
    });
}

function closeTopSlider(){
    $('#top_menu').stop(true,true).fadeOut(1600);
    $('#top_header_area_container').removeClass("opened").stop(true,true).animate({height:0+"px"},2100,'easeInOutBack',function(){
         jwplayer().stop();
         if($("#slide-menu").length>0){
             runSlideMenuAnimation();
         }
    });
    $('#right_ufo_image').children(".right_ufo").stop(true,true).fadeOut(1050,function(){
        $('#right_image_load').stop(true,true).fadeIn(1050);
    });
}

//funcybox function
function fireFuncybox(){
    var transType = (IE7 || IElt6) ? 'fade' : 'elastic';
    $("a.fancybox").fancybox({
        'transitionIn'          :	transType,
        'centerOnScroll'        :       true,
        'transitionOut'         :	transType,
        'easingIn'              :       'easeInOutBack',
        'easingOut'             :       'easeInOutBack',
        'hideOnContentClick'    :       true,
        'speedIn'               :	540,
        'speedOut'              :	240,
        'overlayShow'           :	false,
        'padding'               :       0,
        'titleShow'             :       false
    });
    $("a.fancybox_video").click(function() {
        $.fancybox({
                'padding'		: 0,
                'autoScale'		: false,
                'transitionIn'          : transType,
                'transitionOut'         : transType,
                'easingIn'              : 'easeInOutBack',
                'easingOut'             : 'easeInOutBack',
                'title'                 : this.title,
                'overlayShow'           : true,
                'width'                 : 680,
                'height'		: 495,
                'speedIn'               : 500,
                'speedOut'              : 200,
                'href'                  : this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
                'type'                  : 'swf',
                'swf'                   : {
                                        'wmode'		: 'transparent',
                                        'allowfullscreen'	: 'true'
                                        }
        });
        return false;
    });
}

function rightSubMenu(page){
    $(".rightSubMenuList li a").removeClass("selected");
    $("span.rightMenuSelected").remove();
    var current_pid = $("#current_pid").html();
    if(current_pid!=""){
        $('.rightSubMenuList li a[name="'+current_pid+'"]').addClass("selected").append('<span class="rightMenuSelected"></span>');
         var curIndexProject = $('.rightSubMenuList li a[name="'+current_pid+'"]').parent("li").index()+1;
         prevNextProject(curIndexProject);
         nextPrevProjectSet(curIndexProject);
    }
    else{
        $(".rightSubMenuList li a").eq(0).addClass("selected").append('<span class="rightMenuSelected"></span>');
        prevNextProject(0);
        nextPrevProjectSet(1);
    }
    $(".rightSubMenuList li a").click(function(){
        $(".rightSubMenuList li a").removeClass("selected");
        $("span.rightMenuSelected").remove();
        $(this).addClass("selected");
        $(this).append('<span class="rightMenuSelected"></span>');
        zone = 2;
        currentMenuOpen('/'+page);
        currentProjectSelected = $(this).parent("li").index();
        var cur_category = $(this).attr("href").split("/")[1];
        var cur_client = $(this).attr("href").split("/")[2];
        //historyCall($(this).attr("href"),$(this).parent("li").index()+1);
        historyCall(cur_category,cur_client);
        prevNextProject($(this).parent("li").index());
        return false;
    });
}

function rightSubMenuCallback(data){
    $('#image-next-photo a,#image-previous-photo a').unbind("click");
    resetProjectSlide();
    $(".projectInside").stop(true,true).animate({"height":"350px"},1100).removeClass("selected");
    $(".projectInside").eq(currentProjectSelected).stop(true,true).css("height","auto").addClass("selected").html(data);
    $(".projectItems").stop(true,true).animate({marginLeft:-(847*currentProjectSelected)},660,function(){
        projectSlide(0);
        fireFuncybox();
        nextPrevProjectSet(currentProjectSelected+1);
        voteClick();
        $(".projectInside").not(".selected").empty();
    });
}

function currentProjectPrevCheck(index){
   var prevProjectSelected = index;
   if(prevProjectSelected>0){
       prevProjectSelected--;
   }
   else {
       prevProjectSelected=$('.rightSubMenuList li').length-1;
   }
   return prevProjectSelected;
}

function currentProjectNextCheck(index){
   var nextProjectSelected = index;
   if(index<($('.rightSubMenuList li').length-1)){
       nextProjectSelected++;
   }
   else {
       nextProjectSelected=0;
   }
   return nextProjectSelected;
}

function nextPrevProjectSet(index){
   $('.nextProject').find('.loadProjectLink').fadeOut(0).html($('.rightSubMenuList li').eq(currentProjectNextCheck(index-1)).children("a").text()).fadeIn(300);
   $('.prevProject').find('.loadProjectLink').fadeOut(0).html($('.rightSubMenuList li').eq(currentProjectPrevCheck(index-1)).children("a").text()).fadeIn(300);
}

function prevNextProject(index){
   var totalClients = $('.rightSubMenuList li').length;
   var currentClient = index;

   $('.nextProject a,.nextProject .right_icon').unbind("click").click(function(){
        if(currentClient < totalClients-1){
            currentClient++;
        } else {
            currentClient = 0;
        }
        $(".rightSubMenuList li").eq(currentClient).children("a").trigger("click");
   });
   $('.prevProject a,.prevProject .left_icon').unbind("click").click(function(){
        if(currentClient >0){
            currentClient--;
        } else {
            currentClient = totalClients-1;
        }

        $(".rightSubMenuList li").eq(currentClient).children("a").trigger("click");
   });
}

function resetProjectSlide(){
   $('.projectImageContainer').css("margin","0px");
}

function projectSlide(index){
    var totalImages = $(".projectInside.selected").find('.projectImageContainer .fancyboxItem').length;
    var currentIndex = index;

    $('#image-next-photo a').click(function(){
        if(currentIndex < totalImages-1){
            currentIndex++;
        } else {
            currentIndex = 0;
        }
        moveSlider(currentIndex);
    });

    $('#image-previous-photo a').click(function(){
        if(currentIndex >0){
            currentIndex--;
        } else {
            currentIndex = totalImages-1;
        }
        moveSlider(currentIndex);
    });
}

function moveSlider(Index){
    $('.projectImageContainer').stop(true,true).animate({marginLeft:-(609*Index)},600);
}

//open header
function headerOpen(){
    $("#header_open").toggle(
    function(){
        $("#header_banners").addClass("opened");
        $("#main_menu_container").stop(true,true).animate({"margin-top":"-68px"},{queue:false, duration:600});
        $("#banner1_container").stop(true,true).animate({"height":"418px"},600,function(){
            $(".hoverBanner1").fadeIn();
            slideshow();
        });
        $("#banner2_container").animate({"height":"290px"},600,function(){
            $(".hoverBanner2").fadeIn();
        });
        $("#main_header").stop(true,true).animate({"margin-bottom":"140px"},{queue:false, duration:600});
        $("#bottom_header").stop(true,true).animate({"top":"0px"},600);
        $(".loader").css("top","672px");
    },
    function(){
        $("#header_banners").removeClass("opened");
        $("#main_menu_container").stop(true,true).animate({"margin-top":"-156px"},{queue:false, duration:300});
        $("#banner1_container").stop(true,true).animate({"height":"282px"},300,function(){
            clearInterval(timer);
        });
        $("#banner2_container").stop(true,true).animate({"height":"154px"},{queue:false, duration:300});
        $("#main_header").stop(true,true).animate({"margin-bottom":"50px"},{queue:false, duration:300});
        $("#bottom_header").stop(true,true).animate({"top":"-96px"},{queue:false, duration:300});
        $(".hoverBanner1,.hoverBanner2").fadeOut();
        $(".loader").css("top","542px");
    });
}

function banner2Hover(){
    $(".hoverBanner2").hover(
       function()
       {
            hover2enable();
       },
       function()
       {
            hover2disable();
       }
    );
}

function hover2enable(){
    $(".banner2over").stop(true,true).fadeTo(650,0.9);
    $(".client_text").stop(true,true).fadeIn(850);
}

function hover2disable(){
    $(".client_text").stop(true,true).fadeOut(500);
    $(".banner2over").stop(true,true).fadeOut(550);
}

function slideshow(){
    clearInterval(timer);
    timer = setInterval('slideHeaderImages()',4500);
}

function slideHeaderImages(){
    $('#slideshow_content .slide_image').eq(0).stop(true,true).fadeOut(1250)
     .next('.slide_image').fadeIn(1250)
     .end().appendTo('#slideshow_content');
}

function projectScrollMenu(){
        var bodyScrollTop
        if(isiPad || isiPhone){
            bodyScrollTop = $('body').scrollTop();
        }
        else{
            bodyScrollTop = $(window).scrollTop();
        }
        if(bodyScrollTop>460){
            $('#slide-menu').css({
            top:airFlag + bodyScrollTop - $("#first_content").height()
            }).stop(true,false).fadeIn(350);
        }
        else{
            $('#slide-menu').css({
            top:"10px"
            }).stop(true,false).fadeIn(350);
        }

        $(document).scroll(function () {
            runSlideMenuAnimation();
        });

        $(document).resize(function () {
            runSlideMenuAnimation();
        });
}

function runSlideMenuAnimation(){
    $('#slide-menu').stop(true,false).fadeTo(0,1);
    var bodyScrollTop
    if(isiPad || isiPhone){
        bodyScrollTop = $('body').scrollTop();
    }
    else{
        bodyScrollTop = $(window).scrollTop();
    }
    if(bodyScrollTop>480 && bodyScrollTop<=($("#first_content").height()+$("#top_header_area").height()+$("#main_header").height())-airFlag){
        if($("#top_header_area").height()>0){
            $('#slide-menu').stop(true,false).animate({top: (bodyScrollTop-$("#top_header_area").height()) - (2*airFlag)},1200);
        }
        else{
            $('#slide-menu').stop(true,false).animate({top: bodyScrollTop - (2*airFlag)},1200);
        }
    }
    if(bodyScrollTop<=480){
        $('#slide-menu').stop(true,false).animate({top:10+"px"},1200);
    }
    if(bodyScrollTop>($("#first_content").height()+$("#top_header_area").height()+$("#main_header").height())-airFlag){
        $('#slide-menu').stop(true,false).animate({top:($("#first_content").height())-airFlag+"px"},1200);
    }
}

function miniMenuClick(){
    $("#mini_menu_label a").unbind("click").toggle(
    function(){
        $("#mini_menu_label").addClass("opened");
        $("#slide-menu ul.mini_menu").stop(true,true).slideDown(400);
    },
    function(){
        $("#slide-menu ul.mini_menu").slideUp(200,function(){
            $("#mini_menu_label").removeClass("opened");
        });
    });
    if(!isiPad || !isiPhone){
        miniMenuSelect();
    }
    projectScrollMenu();
}

function voteClick(){
    $(".projectVotes .vote_icon").unbind("click").click(function(){
       var project_id = $(".projectInside.selected").find(".projectVotes").children(".project_id").html();
       var votes = parseInt($(".projectInside.selected").find(".projectVotes").find("span.votes_number").html());
       $.ajax({
          type: "GET",
          url: '/vote.php',
          data: {project_id:project_id},
          success: function(data){
              if(data==1){
                  $(".projectInside.selected").find(".vote_resault").html('Thanks for voting!').fadeIn(500,function(){
                      $(".projectInside.selected").find(".projectVotes span").html(++votes);
                  });
              }
              else {
                  $(".projectInside.selected").find(".vote_resault").html('Already voted...').fadeIn(500);
              }
          }
        });
       return false;
    });
}

function documentSlideDown(){
  if($('.people_container .opened').length==1){
      $('html,body').animate({scrollTop: ($("#main_content").position().top + $(".people_container .opened").position().top) - 40+"px"},800);
  }
  else{
      $('html,body').animate({scrollTop: $("#main_content").position().top - 40+"px"},700);
  }
}

/*
//ipad load images workaround

function loadCanvasImg(src, container) {

        var cnv = document.createElement("canvas"),
                ctx = cnv.getContext("2d"),
                image = new Image();

        image.src = src;

        image.onload = function() {
                cnv.width = image.width;
                cnv.height = image.height;

                ctx.drawImage(image,0,0);

                var span = container;
                span.appendChild(cnv);
        }

}

function drawImagesFix() {
    $(".canvas").each(function() {
            loadCanvasImg($(this).attr("data-src"), this);
    });
}
*/

