/*!
 * jQuery Tools v1.2.5 - The missing UI library for the Web
 * 
 * toolbox/toolbox.expose.js
 * 
 * NO COPYRIGHTS OR LICENSES. DO WHAT YOU LIKE.
 * 
 * http://flowplayer.org/tools/
 * 
 */
(function(a){a.tools=a.tools||{version:"v1.2.5"};var b;b=a.tools.expose={conf:{maskId:"exposeMask",loadSpeed:"slow",closeSpeed:"fast",closeOnClick:!0,closeOnEsc:!0,zIndex:9998,opacity:.8,startOpacity:0,color:"#fff",onLoad:null,onClose:null}};function c(){if(a.browser.msie){var b=a(document).height(),c=a(window).height();return[window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth,b-c<20?c:b]}return[a(document).width(),a(document).height()]}function d(b){if(b)return b.call(a.mask)}var e,f,g,h,i;a.mask={load:function(j,k){if(g)return this;typeof j=="string"&&(j={color:j}),j=j||h,h=j=a.extend(a.extend({},b.conf),j),e=a("#"+j.maskId),e.length||(e=a("<div/>").attr("id",j.maskId),a("body").append(e));var l=c();e.css({position:"absolute",top:0,left:0,width:l[0],height:l[1],display:"none",opacity:j.startOpacity,zIndex:j.zIndex}),j.color&&e.css("backgroundColor",j.color);if(d(j.onBeforeLoad)===!1)return this;j.closeOnEsc&&a(document).bind("keydown.mask",function(b){b.keyCode==27&&a.mask.close(b)}),j.closeOnClick&&e.bind("click.mask",function(b){a.mask.close(b)}),a(window).bind("resize.mask",function(){a.mask.fit()}),k&&k.length&&(i=k.eq(0).css("zIndex"),a.each(k,function(){var b=a(this);/relative|absolute|fixed/i.test(b.css("position"))||b.css("position","relative")}),f=k.css({zIndex:Math.max(j.zIndex+1,i=="auto"?0:i)})),e.css({display:"block"}).fadeTo(j.loadSpeed,j.opacity,function(){a.mask.fit(),d(j.onLoad),g="full"}),g=!0;return this},close:function(){if(g){if(d(h.onBeforeClose)===!1)return this;e.fadeOut(h.closeSpeed,function(){d(h.onClose),f&&f.css({zIndex:i}),g=!1}),a(document).unbind("keydown.mask"),e.unbind("click.mask"),a(window).unbind("resize.mask")}return this},fit:function(){if(g){var a=c();e.css({width:a[0],height:a[1]})}},getMask:function(){return e},isLoaded:function(a){return a?g=="full":g},getConf:function(){return h},getExposed:function(){return f}},a.fn.mask=function(b){a.mask.load(b);return this},a.fn.expose=function(b){a.mask.load(b,this);return this}})(jQuery);

$.contentCache = {};
var _documentTitle = '';
var _glossaryTimer;


function randomBoxChange() {
    $("#boxes .box:visible:random").fadeTo('slow', 0, function() {
        timer();
        
    });
}

function glossBoxChange() {
    var element = $(".pinkBox .gloss.visible");
    var next = element.next('.gloss');
    
    if (!next.length) {
        next = $(".pinkBox .gloss:first");
    }
    
    element.fadeOut('fast', function() {
        element.removeClass('visible');
        next.fadeIn().addClass('visible');
        timerGloss();
                    
    });
    
}

function boxesSize() {
    var boxesWidth = Math.floor($(window).width()/240)*240; // 240 = box width
    //$("#boxes").css("width", boxesWidth);
    
}

function initMap() {
    // load map
   
    //var latlng = new google.maps.LatLng(50.07871453820697, 14.43503737449646);
    var latlng = new google.maps.LatLng(50.078771, 14.434895);
    var myOptions = {
        zoom: 17,
        center: latlng,
        mapTypeControl: false,
        zoomControl: false,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    
    var map = new google.maps.Map(document.getElementById("map"),
    myOptions);
    
    var image = '/user/public/default/images/mapsIco.png';
    var officeMarker = new google.maps.Marker({
        position: latlng,
        map: map,
        icon: image
    });     
}

function ajaxContentPosition() {

    var browserWidth = $(window).width();
    var minus = 0;
    
    $("html, body").animate({scrollTop: 0});
    var ajaxThingsHeight = $(window).height()-120; // minus header height 
    
    /*var boxesNumber = Math.floor(browserWidth/240); // 240 = box width 
    var firstBoxOffset = $("#boxes .box:first").offset().left;    
    
    // position ajax content to second or first box according to window size
    var boxxesNumberResolution = 2;
    if (boxesNumber === 4 || boxesNumber === 5) {
        boxxesNumberResolution = 1;
    }
    
    if (boxesNumber === 8) {
        boxxesNumberResolution = 3;
    }
    
    var leftMargin = (boxxesNumberResolution*240)+firstBoxOffset;

*/

    var leftMargin = $("#boxContent").offset().left+240;
    $("#ajaxContent, #overlay .fade").css({marginLeft: leftMargin});
        
    $("#overlay").height(ajaxThingsHeight);
    
}

function timerIndexBox() {
    setTimeout('randomBoxChange()', 5000);
}

function timerGloss() {
    _glossaryTimer = setTimeout('glossBoxChange()', 14000);
}

function afterContentLoaded(data) {
    // posision content correctly
    ajaxContentPosition();
    
    if (!$("#toUvodLi").length) {
        $("#menu").prepend('<li id="toUvodLi" style="display: none;"><a id="toUvod" href="#"><span>Na úvod</span></a></li>');
    }
    
    $("#toUvodLi").fadeIn();
    
    $("#toUvod").click(function(e) {
        e.preventDefault();
        closeOverlay();
        
    });
    
    // new active class
    $("#"+data.menu).parent().addClass('active');
    
    // remove loading
    $("#overlay").removeClass('active').addClass('loaded');
    
    // fade in content and set page title
    $('#ajaxContent').fadeIn('slow').html(data.text);
    $("#overlay .fade").fadeIn('slow');
    document.title = data.title+' | '+_documentTitle;
    
    // custom for pages    
    if ($("#map").length) {
        initMap();
    }
    
    if ($("#player").length) {
          
      	flowplayer("player", "http://spindoctors.cz/user/public/default/scripts/flowplayer/flowplayer.commercial-3.2.7-3.swf", {
      		wmode: 'transparent',
      		clip: {    
      			provider: 'lighttpd'
      		},
      		plugins: {
      			lighttpd: {
      				url: 'http://spindoctors.cz/user/public/default/scripts/flowplayer/flowplayer.pseudostreaming-3.2.7.swf'
      			}
      		},
          play: { 
              replayLabel: 'Přehrát znovu' 
          }			
      	});	          
       
        if (autoPlay == true) {
            flowplayer("player").play();
            autoPlay = null;
        }       
        
    }
    
    
    if ($('#glossesChanging').length) {
        clearTimeout(_glossaryTimer);
        timerGloss();
        
        
      if (singleGloss) {
            $(".glossBox li:not(#"+singleGloss+")").hide();
            
            //$(".glossBox").append('<a href="#" id="showotherslings">Zobrazit ostatní výrazy od <strong>'+$("#letters a.active").text()+'</strong></a>');
            
           /* $("#showotherslings").click(function(e) {
               $(this).remove();
               $(".glossBox li").show(); 
                
            });*/
            
            singleGloss = null;
            
        }
    }
    
    if ($("#serviceLinkThru").length) {
        $("#serviceLinkThru a").click(function(e) {
            e.preventDefault();
            
            ajaxAction($(this).attr("href"));
            
        });
        
        $("#backToService").click(function(e) {
            e.preventDefault();
            
            ajaxAction($(this).attr("href"));
            
        });
        
    }
    
    if ($("#search").length) {
        $(".searchLinks a:not(.noAjax a, .glossary a)").click(function(e) {
            e.preventDefault();
            
            ajaxAction($(this).attr("href"));
            
        });
    
        $(".glossary a").click(function(e) {
            e.preventDefault();
            singleGloss = $(this).attr("rel");
            ajaxAction($(this).attr("href"));
        });  
    }
    
    
    
    if ($("#sitemapul").length) {
        //console.log("fdsf");
        $("#sitemapul a").not("#blogslink a").click(function(e) {
            e.preventDefault();
            
            ajaxAction($(this).attr("href"));
            
        });
        
    }

}

function ajaxAndCache(href) {
    if (!$.contentCache[href]) {
    
        $.get(href, function(returnData) {
            afterContentLoaded(returnData);
            
            // add content to cache with url as a key
            $.contentCache[href] = returnData;
            
        }, 'json').error(function() { 
            alert("404"); 
            
        });
        
    } else {
        afterContentLoaded($.contentCache[href]);
        
    }

}

function closeOverlay() {
    if ($("#overlay").hasClass('loaded')) {
        
        $("#toUvodLi").fadeOut(function() {
           $(this).remove(); 
        });
        
        $("#overlay").fadeOut('fast', function() {
            $(this).removeClass('loaded').removeAttr('style');
            $("#menu .active").removeClass('active');    
            
            $("#ajaxContent").html(''); 
            
            window.location.hash = '';   
			$("body").css({overflow: 'visible'});
            $("body").css("margin", 0);
			document.title = _documentTitle;
            
            _glossaryTimer = null;
            
            glossChange();
        });
        
    } else {
        window.location = "/";
        
    }
    
}

function ajaxAction(href) {
    window.location.hash = '#!'+href;
    $.mask.close(); 
    // new active class
    $("#menu li.active").removeClass('active');
    
    // stop changing glossary on index
    clearTimeout(_indexGlossaryTimer)
    
    if ($("#overlay").hasClass('loaded')) {
        // fade out and clear current content
        $("#ajaxContent").fadeOut(100, function() {
            ajaxAndCache(href);
        });
        
        $("#overlay .fade").fadeOut(100);
        
    } else {
        $("body").css({overflow: 'hidden'});
        
        if ($(document).height() > $(window).height()) {
            $("body").css("marginRight", "16px");
        }
        // loading animation + fade in overlay
        $("#overlay").addClass('active').fadeIn('fast');
        
        ajaxAndCache(href);
    }
}

/*
function glossChange() {
    
    _indexGlossaryTimer = setTimeout(function() {
        $.get('/glossary/random/', function(data) {
            $("#lingoAjax").fadeOut("fast", function() {
                $(this).html(data).fadeIn();
                
            });
            
        });   
         
        glossChange();
        
    }, 6000);    
    
}*/

var singleGloss;
var autoPlay;

$(document).ready(function() {
    _documentTitle = document.title;
    
    //glossChange();
    
    
    $("#searchSubmit").click(function(e) {
        e.preventDefault();
        var input = $("#searchInput");
        var val = input.val();
        
        if (val) {
            ajaxAction("/vyhledavani/"+val);
            
        } else {
            input.addClass("error");
            
        } 
        
    });
    
    $("#closeOverlay").live("click", function(e) {
        e.preventDefault();
        $("#searchInput").val("");
        closeOverlay();
    });
    
    $("#searchInput").focus(function() {
       $(this).removeClass("error");
        
    });
    
    $("#lingo h3 a").live("click", function(e) {
        e.preventDefault();
        
        var element = $(this);
        var href = element.attr('href');
        
        if (href != '#') {
            //menuClickFunction(element);
            singleGloss = element.attr("rel");
            
            ajaxAction(href);
            
            
        }
    });
    
    if (navigator.geolocation) {
        $("li.adress").live("click", function() {
            navigator.geolocation.getCurrentPosition(
                function(position) {
                    window.location = 'http://maps.google.cz/maps?saddr='+position.coords.latitude+','+position.coords.longitude+'&daddr=vinohradsk%E1%20403/17%20praha%202';
                    
                
                }, 
                function() {
                
                    alert("Není možné zjistit vaší pozici");
                }
            );    
            
        })
    }

    $(".servicesWrap li a").live('click', function(e) {
        e.preventDefault();
        
        ajaxAction($(this).attr('href'));
        
    });
    
    // if there's an active hash on load redirect to it
    var windowHash = window.location.hash;
    if (window.location.hash) {
    	var href = windowHash.slice(2)

        ajaxAction(href);

    }
    
    $("#letters a").live('click', function(e) {
        e.preventDefault();
        var element = $(this);
        var href = element.attr('href');
        
        
        //if (!element.hasClass('active')) {
            $("#letters a.active").removeClass('active');
            element.addClass('active');
            
            var result = '';
            
            if (!$.contentCache[href]) {
            
                $.get(href+'?switch=true', function(returnData) {
                    /*$("#showotherslings").remove();*/
                    
                    $(".glosses").html(returnData.text);
                    
                    // add content to cache with url as a key
                    $.contentCache[href] = returnData;
                    
                }, 'json');
                
            } else {
                var glosses = $('.glosses', $($.contentCache[href].text)).html();
                
                if (!glosses) {
                    glosses = $.contentCache[href].text;    
                }
                
                $(".glosses").html(glosses);
                //$("#showotherslings").remove();
                //$(".glossBox li").show();
                
            }
            
            $(".glossBox li").show();
    
            window.location.hash = '#!'+element.attr('href');
        //}
        
    });
    
    $(".boxLink a").click(function(e) { 
       if ($(this).attr("href")) {
            e.preventDefault();
            
            ajaxAction($(this).attr("href"));
        
       }
    });
    
    $("#logo").click(function(e) {
        e.preventDefault();
        
        closeOverlay();
        
    });

	$.each($('.fadein'), function(index) {
	   $(this).css('opacity', '0').delay(120*index).fadeTo(500, 1, function() {
	       $(this).removeAttr("style");
           
	   });

	});
    
    // form send button
    $("#sendForm").live("click", function(e) {
        e.preventDefault();
        
        var error = false;
        $.each($("#contactForm .required"), function() {
          if (!$(this).val()) {
            error = true;
            
            $(this).addClass('error');
          }  
            
        });
        
        if (!error) {
            $.post('/mail/send', $('#contactForm').serialize(), function(returnData) {
                alert("odesláno");
                $("#contactForm input, #contactForm textarea").val('');    
            });
            
        }
    });
    
    $(".required.error").live("focus", function() {
       $(this).removeClass("error");
    });
    
    var _exposeTimeOut;
    $(".fadein").hover(function() {
        var element = $(this);
       _exposeTimeOut = setTimeout(function() {
        element.expose({opacity: 0.88, loadSpeed: 300}); 
       }, 3500);
       
        
    },function() {
        clearTimeout(_exposeTimeOut);
       $.mask.close(); 
        
    });
    // timer();
    
    boxesSize();
    $(window).resize(function() {
        boxesSize(); 
        
        if ($("#overlay").is(':visible')) {
            ajaxContentPosition();
            
        }
    });
    
    $("#menu a:not(.noAjax), #legal, #sitemap, #referencesWrap a").click(function(e) {
        e.preventDefault();
        var element = $(this);
        var href = element.attr('href');
        
        if (href != '#') {
            //menuClickFunction(element);
            ajaxAction(href);
        }
    });
    
    $("#videoPlay").click(function(e) {
        e.preventDefault();
        var element = $(this);
        var href = element.attr('href');
        
        if (href != '#') {
            //menuClickFunction(element);
            autoPlay = true;
            ajaxAction(href);
        }
        
    });
    
    $("#searchInput").attr("autocomplete", "off");
    
    $(".boxLink").bind("mouseover click", function() {
        clearTimeout(_exposeTimeOut);
    });
    
});
