(function ($) {
  
  var flashInited = false;
  
  var videoSeenCookie = $.cookie("videoSeenIds");
  window.videoSeenIds = videoSeenCookie ? videoSeenCookie.split(/,/) : [];
  
  SWFAddress.addEventListener(SWFAddressEvent.INIT,function() {
    if (window.console)
      console.log("init");
  });
  
  var bindNoFlash = function () {
    //navigation links
    $("#menu li a, #top h1 a").click(function () {
      var self = $(this), rel;
      if (rel = self.attr("rel")) {
        setPage(rel);
      } else {
        if (self.is("#menu_03 a")) {
          openVideoOverlay(0,"Video of the Day","Video of the Day");
        }
      }
      return false;	
    });
  }
  
  var afterInitFlash = function (e) {
    //navigation links
    var footer_links = $("#bottom li a").click(function () {
      var self = $(this), rel;
      footer_links.removeClass("on");
      if (rel = self.attr("rel")) {
        setPage(rel);
        return false;
      }
    });
    
    if(e.success) {
      if (window.console)
        console.log("initFlash successful");
      return;
    }
    if (window.console)
      console.log("initFlash failed");
    //bind non flash events
    $("html").addClass("noFlash");
    $(bindNoFlash);
  }
  
  var initFlash = function (pageName) {
    if (window.console)
      console.log("initFlash "+pageName);
    var flashVars = {
      currentSession: pageName.replace(/^\//,""), //"crew" "games" "skills"
      pageFn: "setPage",
  	  service: "../php/gateway.php"
    };
    
    swfobject.embedSWF("./swf/HomeMenu.swf", "top", "900", "373", "10.0.0", "./swf/expressInstall.swf", flashVars, {wmode:"transparent"}, {}, afterInitFlash);
    swfobject.embedSWF("./swf/Footer.swf", "bottom", "900", "193", "10.0.0", "./swf/expressInstall.swf", flashVars, {wmode:"transparent"});
  }
  
  window.setPage = function (pageName) {
    if(window.console)
      console.log("setPage "+pageName);
    SWFAddress.setValue(pageName);
  }
  window.trackEvent = function (category, action, opt_label, opt_value) {
    _gaq.push(['_trackEvent', category, action, opt_label, opt_value]);
  }
  window.closeOverlay = function() {
    $.fancybox.close();
  };
  window.openVideoOverlay = function (id,category,title) {
    _gaq.push(['_trackEvent', category, 'Play', id+" "+title]);
    var default_opts = {
      autoDimensions: false,
      width: 865,
      height: 625,
      autoScale: false,
      padding: 0,
      margin: 0,
		  overlayOpacity: 0.48,
      overlayColor: "#000",
      onClosed: function () {
        _gaq.push(['_trackEvent', category, 'Close', id+" "+title]);
      }
    };
    if (!$("html").is(".noFlash")) {
      $.extend(default_opts, {
        href: "swf/OverlayPlayer.swf",
        type: "swf",
        transitionIn: 'none',
			  transitionOut: 'none',
        swf: {
          flashvars: "video_id=video_"+id+"&closeFn=closeOverlay&path="+SWFAddress.getValue(),
          wmode: "opaque",
		      allowFullScreen: "true",
		      bgcolor: "#000000"
        },
        showCloseButton: false
      });
    } else {
      $.extend(default_opts, {
        width: 834,
        height: 508,
        content: '<div id="noFlashOverlayContainer"><div id="games_noflash"><p>'+fruitshoot_i18n.videos_no_flash_1+'</p><p>'+fruitshoot_i18n.videos_no_flash_2+'</p><p><a class="external" href="http://www.adobe.com/go/getflashplayer" title="Get Adobe Flash Player"><img src="images/get_adobe_flash_player.png" width="158" height="39" alt="Get Adobe Flash Player" /></a></p></div></div>'
      });
    }
    
    $.fancybox(default_opts);
    
  }
  window.videoSeen = function(id) {
    if (window.console)
      console.log("video seen",id);
    if($.inArray(id,videoSeenIds) == -1) {
      videoSeenIds.push(id);
      $.cookie("videoSeenIds", videoSeenIds.join(","), {expires: 365});
    }
    $("#"+id).closest("li").addClass("viewed");
  }
  window.openGameOverlay = function (id,title) { 
    _gaq.push(['_trackEvent', 'Games', 'Open', id+" "+title]);
	try{
		document.getElementById('top').stopEverything();
		document.getElementById('bottom').stopEverything();
	}
	catch(err)
	{
		if (window.console)
      			console.log(err);
	}

    var opts = {
      autoDimensions: false,
      width: 834,
      height: 508,
      autoScale: false,
	  overlayOpacity: 0.48,
      overlayColor: "#000",
      padding: 0,
      margin: 0,
      href: "games/"+id+"test.swf",
      type: "swf",
      swf: {
        flashvars: "game_id="+id+"test"+"&closeFn=closeOverlay&service=../php/gateway.php",
        wmode: "transparent",
	      allowFullScreen: "true"
      },
      showCloseButton: false,
	  hideOnOverlayClick: false,
	  
		
	  
      onClosed: function () {
      	document.getElementById('games').resetMenu();
      	try{
			document.getElementById('top').playEverything();
			document.getElementById('bottom').playEverything();
		}
		catch(err)
		{
			if (window.console)
      			console.log(err);
		}
        _gaq.push(['_trackEvent', 'Games', 'Close', id+" "+title]);
		$.fancybox.hideActivity();
      }
    };
    $.fancybox(opts);
	$.fancybox.showActivity();
  }
  var pageHandler = function (e) {
    if (window.console)
      console.log("page change ",e);
    _gaq.push(['_trackEvent', 'Page', 'Change', e.value]);
    if (!flashInited) {
      flashInited = true;
      initFlash(e.value);
    }
    var url = "", bodyClass = "";
    $("#bottom li a").removeClass("on");
    $.fancybox.close();
    switch(e.value) {
      case "/skills":
        url = "./ajax_videos.php";
        bodyClass = "videos";
        break;
      case "/crew":
        url = "./ajax_juice_crew.php";
        bodyClass = "videos";
        break;
      case "/games":
        url = "./ajax_games.php";
        bodyClass = "videos";
        break;      
      case "/termsandconditions":
        url = "./ajax_termsandconditions.php";
        bodyClass = "videos";
        $("#bottom li a[rel=/termsandconditions]").addClass("on");
        break;
      case "/privacy":
        url = "./ajax_privacy.php";
        bodyClass = "videos";
        $("#bottom li a[rel=/privacy]").addClass("on");
        break;
      case "/":
        url = "./empty.html";
        bodyClass = "home";
        break;
    }
    if (window.console)
      console.log("load page "+url);
    if(url)
      $.ajax({
        url: url,
        success: function(data) {
          $(function () {
            $("body").attr("class",bodyClass);
            $("#main_content").html(data);
            $("html,body").animate({scrollTop:0},500);
            $("a.back").unbind("click").click(function () {
              SWFAddress.back();
              return false;
            });
          });
        }
      });
    $(function () {
      $("a.external").attr("target","_blank");
      //language selection
      var langs = $("#lang");
      var flags = langs.find("li:not(.first)");
      var current = langs.find("li.first");
      langs.find("a.choose").click(function () {
        if(flags.height()) {
        	flags.animate({height:0},"fast");
        } else {
        	flags.not(".last").animate({height:"18px"},"fast");
        	flags.filter(".last").animate({height:"2px"},"fast");
        }
        
        return false;
      });
      flags.find("a").click(function () {
        current = $(this).closest("li").clone(true).addClass("first").replaceAll(current);
        flags.slideToggle("fast");
        window.location = $(this).attr("href");
        return false;
      });
    })
  }
  
  SWFAddress.addEventListener(SWFAddressEvent.CHANGE,pageHandler);
})(jQuery);

