/*
Sitewide JS
*/



function popUpBlockHandler(openFunction, whatTried){
    $("body").append("<div id=\"dialog\" title=\"Pop-Up Blocker Detected\"><p style=\"width:250px;\">The "+whatTried+" tried to open a new window, but was blocked. Click \"Show Window\" to open.</p></div>");
    $("#dialog").dialog({
        bgiframe: true,
        resizable: false,
        width:300,
        height:200,
        modal: true,
        overlay: {
            backgroundColor: '#000',
            opacity: 0.75
        },
        buttons: {
            Cancel: function() {
                $(this).dialog('close');
            },
            "Show Window": function() {
                openFunction();
                $(this).dialog('close');
            }
        }
    });
}

function launchPopup(thisURL,windowName,width,height,left,top){
    var openFunction=function(){

        evbListen = open("", windowName, "width="+width+",height="+height+",toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable,left="+left+",top="+top+"");
        if(!evbListen || evbListen.closed || !evbListen.thisBodyId){
            evbListen = window.open(thisURL, windowName, "width="+width+",height="+height+",toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable,left="+left+",top="+top+"");
        } else evbListen.focus();

        // evbListen = window.open( thisURL,windowName,"width="+width+",height="+height+",toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable,left="+left+",top="+top+"");
        if((evbListen!=null) && (typeof evbListen!="undefined")){
            evbListen.focus();
            return true;
        }
    }
    successfulOpen=openFunction();
    if(!successfulOpen){
        popUpBlockHandler(openFunction,"\"Listen\" player");
    }
}



/*
Gallery Index JS
*/

function initializeGalleryIndex(){
    $("#content li > a").each(function(i){
        $("img", this).addClass("thumb");
        thisImageName = $("img", this).attr("alt");
        $(this).css({zIndex:"2"}).append("<img class=\"bg\" src=\"/images/galleries/index_bg/" + thisImageName + ".jpg\">");
        $("img.bg", this).css({opacity:"0",zIndex:"-1",position:"absolute",left:"0",top:"0",border:"0"});
    });
    $("a").mouseover(function(){
        if($.browser.msie && parseInt($.browser.version) <= 6){
            $("img.thumb", this).css({border:"1px solid #fff",left:"-1px",top:"13px"});
        }
        $("img.bg", this).css({opacity:"0.25"});
    }).mouseout(function(){
        if($.browser.msie && parseInt($.browser.version) <= 6){
            $("img.thumb", this).css({border:"0",left:"0",top:"14px"});
        }
        $("img.bg", this).css({opacity:"0"});
    }).click(function(){
        $("img.bg", this).animate({opacity:"0.5"}, 100, function(){
            $(this).animate({opacity:"0.25"}, 100);
        });
    });
};



/*
Gallery JS
*/

if($.browser.msie){
    flashVersionRequired = "9.0.124";
}else{
    flashVersionRequired = "9";
}
current_section = default_section = "current";
anchors = ["cu","ch","dl"];
sections = ["current","change","download"];
h2_offsets = ["0px","-200px","-400px"];
jQuery.easing.def = "easeInOutQuart";
cu_position = ch_position = false;
if(!Array.indexOf){
    Array.prototype.indexOf = function(obj){
        for(var i=0; i<this.length; i++){
            if(this[i]==obj){
                return i;
            }
        }
        return -1;
    }
}
function changeSection(new_section,i,changeSpeed){
    if(changeSpeed === undefined) changeSpeed = 400;
    if(new_section !== current_section){
        if(new_section !== "full"){
            $(".gallery_controls #" + new_section + " h2").css({backgroundPosition:h2_offsets[i] + " -25px",cursor:"default"});
            $(".gallery_controls #" + current_section + " h2").css({backgroundPosition:h2_offsets[sections.indexOf(current_section)] + " 0",cursor:""});
            if(current_section == "current"){
                if(new_section == "change"){
                    $(".gallery_controls #change").animate({top:"-441px"}, changeSpeed, "easeOutExpo");
                }else if(new_section == "download"){
                    $(".gallery_controls #change").animate({top:"-441px"}, changeSpeed, "easeOutExpo");
                    $(".gallery_controls #download").animate({top:"-882px"}, changeSpeed, "easeOutExpo");
                }
            }else if(current_section == "change"){
                if(new_section == "current"){
                    $(".gallery_controls #change").animate({top:"0"}, changeSpeed, "easeOutExpo");
                }else if(new_section == "download"){
                    $(".gallery_controls #download").animate({top:"-882px"}, changeSpeed, "easeOutExpo");
                }
            }else if(current_section == "download"){
                if(new_section == "current"){
                    $(".gallery_controls #change").animate({top:"0"}, changeSpeed, "easeOutExpo");
                    $(".gallery_controls #download").animate({top:"-441px"}, changeSpeed, "easeOutExpo");
                }else if(new_section == "change"){
                    $(".gallery_controls #download").animate({top:"-441px"}, changeSpeed, "easeOutExpo");
                }
            }
            new_href = $(".previous_next .previous a").attr("href");
            if(new_href){
                new_href = new_href.split("#")[0];
                if(new_section !== default_section){
                    new_href = new_href + "#" + anchors[sections.indexOf(new_section)];
                }
                $(".previous_next .previous a").attr("href", new_href);
            }
            new_href = $(".previous_next .next a").attr("href");
            if(new_href){
                new_href = new_href.split("#")[0];
                if(new_section !== default_section){
                    new_href = new_href + "#" + anchors[sections.indexOf(new_section)];
                }
                $(".previous_next .next a").attr("href", new_href);
            }
            current_section = new_section;
        }
    }
}
function modify_px_value(originalValue,desiredChange){
    originalValue=parseInt(originalValue.substring(0,originalValue.length-2))+desiredChange;
    return originalValue+"px";
}
function getGalleryState(){
    return current_section;
}
function setGalleryState(name,control_section,reloadDelay){
    if(window.location.pathname != "/galleries/"+name+"/" && window.location.pathname.slice(0,-21) != "/galleries/"+name+"/"){
        window_location = "/galleries/"+name+"/";
        if(window.location.pathname.slice(-21) == "test_setgallerystate/"){
            window_location += "test_setgallerystate/";
        }
        if(control_section !== default_section){
            window_location += "#" + anchors[sections.indexOf(control_section)];
        }
        reloadDelay = parseInt(reloadDelay);
        if(reloadDelay > 0){
            setTimeout("window.location = window_location;",reloadDelay);
        }else{
            window.location = window_location;
        }
    }else{
        if(control_section !== current_section){
            changeSection(control_section,sections.indexOf(control_section),0);
        }
        window.focus();
    }
}
function checkForImages(this_file_name,this_download_less_than_100ppi,this_download_100ppi,this_download_300ppi){
    return $.ajax({
        async: false,
        type:'GET',
        url:'/js/look_for_downloads/',
        data:{file_name:this_file_name,download_less_than_100ppi:this_download_less_than_100ppi,download_100ppi:this_download_100ppi,download_300ppi:this_download_300ppi}
    }).responseText;
}
function initializeGallery(){
    thisURL = document.location.toString();
    if (thisURL.match("#")) {
        thisAnchor = thisURL.split("#");
        thisAnchor = anchors.indexOf(thisAnchor[1]);
        if(thisAnchor !== -1) changeSection(sections[thisAnchor],thisAnchor,0);
    }else{
        try{
            $(".gallery_controls #" + current_section + " h2").css({backgroundPosition:h2_offsets[sections.indexOf(current_section)] + " -25px",cursor:"default"});
        }catch(err){
            $(".gallery_controls #" + current_section + " h2").css("background-position-y","-25px").css("cursor","default");
        }
    }
    $(".gallery_controls h2").each(function(i){
        $(this).click(function(){
            new_section = $(this).parent().attr("id");
            changeSection(new_section,i,400);
        });
        if($.browser.msie && parseInt($.browser.version) <= 6){
            $(this).mouseover(function(){
                if($(this).parent().attr("id") == "download"){
                    $(this).css("background-position-y","-26px");
                }else{
                    $(this).css("background-position-y","-25px");
                }
            }).mouseout(function(){
                $(this).css("background-position-y","0");
            });
        }
    });
    $("#current .down").click(function(){
        if($(this).attr("class").substring(5) !== "disabled"){
            if(cu_position === false) cu_position = $("#current .gallery_thumbs").css("top");
            if((-1*parseInt(cu_position.substring(0,cu_position.length-2))) + 518 >= $("#current .gallery_thumbs div:last-child").position().top){
                $(this).addClass("disabled");
            }
            cu_position = modify_px_value(cu_position, -319);
            $("#current .gallery_thumbs").stop(true).animate({top:cu_position}, 700, "easeOutExpo");
            $("#current .up").removeClass("disabled");
        }
        return false;
    });
    $("#current .up").click(function(){
        if($(this).attr("class").substring(3) !== "disabled"){
            if(cu_position === false) cu_position = $("#current .gallery_thumbs").css("top");
            if((-1*parseInt(cu_position.substring(0,cu_position.length-2))) <= 331){
                $(this).addClass("disabled");
            }
            cu_position = modify_px_value(cu_position, 319);
            $("#current .gallery_thumbs").stop(true).animate({top:cu_position}, 700, "easeOutExpo");
            $("#current .down").removeClass("disabled");
        }
        return false;
    });
    $("#change .down").click(function(){
        if($(this).attr("class").substring(5) !== "disabled"){
            if(ch_position === false) ch_position = $("#change .gallery_thumbs").css("top");
            if((-1*parseInt(ch_position.substring(0,ch_position.length-2))) + 648 >= $("#change .gallery_thumbs > div:last-child").position().top){
                $(this).addClass("disabled");
            }
            ch_position = modify_px_value(ch_position, -365);
            $("#change .gallery_thumbs").stop(true).animate({top:ch_position}, 700, "easeOutExpo");
            $("#change .up").removeClass("disabled");
        }
        return false;
    });
    $("#change .up").click(function(){
        if($(this).attr("class").substring(3) !== "disabled"){
            if(ch_position === false) ch_position = $("#change .gallery_thumbs").css("top");
            if((-1*parseInt(ch_position.substring(0,ch_position.length-2))) <= 374){
                $(this).addClass("disabled");
            }
            ch_position = modify_px_value(ch_position, 365);
            $("#change .gallery_thumbs").stop(true).animate({top:ch_position}, 700, "easeOutExpo");
            $("#change .down").removeClass("disabled");
        }
        return false;
    });
    $("a").each(function(){
        if($(this).attr("href") == ""){
            $(this).click(function(){
                return false;
            });
        }
    });
    thisGalleryName = thisURL.split("/galleries/");
    if (thisURL.match("#")) {
        thisGalleryName = thisGalleryName[1].split("#");
        thisGalleryName = thisGalleryName[0];
    }else{
        thisGalleryName = thisGalleryName[1];
    }
    if(thisGalleryName.substring(thisGalleryName.length-1,thisGalleryName.length) == "/"){
        thisGalleryName = thisGalleryName.substring(0,thisGalleryName.length-1);
    }
    swfobject.embedSWF("/swf/gallery.swf", "full_screen_view", "200", "25", flashVersionRequired, false, {xml:"/xml/galleries.xml",name:thisGalleryName}, {menu:"false",allowfullscreen:"true",allowscriptaccess:"always"});
    if($.browser.msie && parseInt($.browser.version) <= 6){
        $(".gallery_controls #current a").mouseover(function(){
            $("img", this).css({border:"2px solid #ff9",position:"absolute",left:"12px",top:"13px"});
        }).mouseout(function(){
            $("img", this).css({border:"0",left:"14px",top:"15px"});
        });
        $(".gallery_controls #change a").mouseover(function(){
            $("img", this).css({border:"2px solid #ff9",position:"absolute",left:"-2px",top:"8px"});
        }).mouseout(function(){
            $("img", this).css({border:"0",left:"0",top:"10px"});
        });
    }
}



function externalLinks(){
	$("a[href^='http://']").attr('title', function(){
			return $(this).attr('title')+' [opens in a new window]'
		}).click(function(){
			window.open($(this).attr('href'));
			return false;
	})
}



/*
Listen JS
*/

function initializeListen(){
    swfobject.embedSWF("/swf/listenStandalone.swf", "listen_player", "235", "331", "9.0.0", false, {xml:"/xml/listen.xml"},{allowscriptaccess:"always"});
}



/*
Home JS
*/

var bufferedEvent = bufferedEventTimer = false;

function sendEvent () {
  if (bufferedEvent !== false) {
    _gaq.push(['_trackEvent', bufferedEvent.category, bufferedEvent.action, bufferedEvent.label, bufferedEvent.value]);
    // console.log('Category: ' + bufferedEvent.category + ', Action: ' + bufferedEvent.action + ", Label: " + bufferedEvent.label + ", Value: " + bufferedEvent.value);
    bufferedEvent = false;
  }
}

function embedYouTubeVideo(elementID, ytID, playerWidth, playerHeight){
    // This code loads the IFrame Player API code asynchronously.
    var tag = document.createElement('script');
    tag.src = "http://www.youtube.com/player_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    
    // This function creates an <iframe> (and YouTube player)
    // after the API code downloads.
    var player;
    window.onYouTubePlayerAPIReady = function () {
      var firstPlay = true,
      player = new YT.Player(elementID, {
        height: playerHeight,
        width: playerWidth,
        videoId: ytID,
        events: {
          'onStateChange': function (event) {
            var eventStrings = {
              category: 'Video',
              action: false,
              label: "on " + window.location.pathname,
              value: false
            };
            if (event.data === YT.PlayerState.PLAYING) {
              if (firstPlay === true) {
                eventStrings.action = "Play";
                firstPlay = false;
              } else {
                eventStrings.action = "Play (continued)";
              }
            } else if (event.data === YT.PlayerState.PAUSED) {
              eventStrings.action = "Pause";
            } else if (event.data === YT.PlayerState.ENDED) {
              eventStrings.action = "End";
            }
            if(eventStrings.action !== false) {
              eventStrings.value = Math.round(event.target.getCurrentTime());
              if (bufferedEvent !== false && bufferedEvent.category === "Video") {
                if (bufferedEvent.action === "Pause" && eventStrings.action === "Play (continued)") {
                  bufferedEvent.action = "Pause (to skip)";
                  eventStrings.action = "Play (after skip)";
                } else if (bufferedEvent.action.substring(0,4) === "Play" && eventStrings.action === "Play (continued)") {
                  // Suppress multiple "Play" events.
                  if (bufferedEvent.action === "Play (after skip)") {
                      eventStrings.action = bufferedEvent.action;
                  }
                  bufferedEvent = false;
                } else if (bufferedEvent.action === "Pause" && eventStrings.action === "End") {
                  // Suppress "Pause" event before "End" event.
                  bufferedEvent = false;
                }
                clearTimeout(bufferedEventTimer);
                // console.log("Pushing buffer...");
                sendEvent();
              }
              bufferedEvent = eventStrings;
              bufferedEventTimer = setTimeout(sendEvent, 1000);
            }
          }
        }
      });
    }
}

function initializeHome(){
    $('#gallery_preview').jScrollPane();
    
    // NovelApp video "popup"
    embedYouTubeVideo("tfbookappvideo", "kRBeT4k88nY", 340, 200);
}



/*
Tracking
*/

function trackOutboundLinks () {
    $("a").each(function(){
        var thisURL = $(this).attr("href");
        if (thisURL && (thisURL.substring(0, 7) === "http://" || thisURL.substring(0, 8) === "https://")) {
            $(this).click(function () {
                _gaq.push(['_trackEvent', 'Outbound', 'Click', thisURL + " from " + window.location.pathname]);
            });
        }
    });
}



$(document).ready(function(){
    $(".navigation .listen a, #site_map_alt a#listen").click(function(){
        launchPopup("/listen/","listen_window",235,317,(screen.width-235),20);
        return false;
    });
    
    thisBodyId = $("body").attr("id");
    
    if(thisBodyId === "home"){
        initializeHome();
    }else if(thisBodyId === "galleries"){
        initializeGalleryIndex();
    }else if(thisBodyId === "gallery"){
        initializeGallery();
    }else if(thisBodyId === "listen"){
        initializeListen();
    }
    externalLinks();
    
    trackOutboundLinks();
});
