$(document).ready(function() {

    // fixup mo states
//    setup_menu();

    // hooks up simple MO handlers to the preview thingy
    if (const_page == "film" ||
        const_page == "commercial" ||
        const_page == "music" ||
        const_page == "extra") {
        $(".view-small-item").mouseover(function () {
            $(this).find(".view-small-item-text").css("display","inline");
        });
        $(".view-small-item").mouseout(function () {
            $(this).find(".view-small-item-text").css("display","none");
        });


        // this will hook into the huge "show movie" function
        $(".view-small-item").click(function() {
            var id = $(this).find("input[name=view_id]").val();
            var baseurl = remove_url_fragment(location.href);
            location.href = baseurl + "#" + id;
            load_film(id);
        });

        // check to see if any id was found in url. otherwise
        // default to first id found in small previews.
        current_id = $(".view-small-item input:eq(0)").val();
        if (contains_url_fragment(location.href) > 0) {
            current_id = extract_url_fragment(location.href);
            // in this case, we also want to shift the scroller, 
            // the appropiate amount for the newly loaded page.
            var films_idx = films_own_idx(current_id);
            if (films_idx > const_view_visible) {
                // how many times?
                var times = Math.floor(films_idx/const_view_visible);
                selector_scrolling = true;
                setTimeout(function() {
                        $("#view-small").scrollTo("+=" + (scroll_amount*times), {duration:500})
                        setTimeout(function() {selector_scrolling = false;}, 600);
                },500);
            }
        }

        // const var is from php, global vars.
        view_selector_text(current_id);

        // hookup scroll events
        $("#view-selector-next").click(scroll_selector);
        $("#view-selector-prev").click(scroll_selector);

        // finally load "onload" film:
        load_film(current_id);
    }

    if (const_page == "index") {
        $("#extra-text-teaser").click(function() {
            $(this).fadeOut(200, function() {
                $("#extra-text-body").fadeIn(500);
            });
        })
    }
});

//var current_menu;
//var flipping_current_menu = false;
//var flipping_timer;
//var flipping_timer_max = 2000;
//var flipping_interval = 200;

//function setup_menu() {
//    // flips all menu items off
//    // reset when moving out
//    var imgs = $("#menu a img");
//    for (var i = 0; i < imgs.length; i++) {
//        if (imgs.get(i).src.match("_on")) {
//            current_menu = imgs.get(i);
//        }
//    }

//    $("#menu a img").each(function() {

//        $(this).mouseover(function() {
//            // identify the current menu item. 
//            // save for later restoration.
//            flipping_current_menu = false;
//            var imgs = $("#menu a img");
//            for (var i = 0; i < imgs.length; i++) {
//                flip_image(false,$(imgs.get(i)));
//            }
//            flip_image(true, $(this));
//        });

//        $(this).mouseout(function() {
//            $(this).attr("src",$(this).attr("src").replace("_on","_off"));
//            flipping_current_menu = true;
//            flipping_timer = new Date().getTime();
//        });
//    });
//}

//window.setInterval(function() {
//    var ts = new Date().getTime();
//    if (flipping_current_menu && (
//        ts - flipping_timer) > flipping_timer_max) {
//        $(current_menu).attr("src",$(current_menu).attr("src").replace("_off", "_on"));
//        flipping_current_menu = false;
//    }
//}, flipping_interval);

function flip_image(turnon, img) {
    if (!turnon) {
        $(img).attr("src",$(img).attr("src").replace("_on","_off"));
    } else {
        $(img).attr("src",$(img).attr("src").replace("_off","_on"));
    }
}

function films_own_idx(id) {
    var inputs = $(".view-small-item input");
    var total = inputs.size();
    var total_pages = selector_pages_max();
    var own_idx = 0; // fall back to 0, if not found ...
    for (var i = 0; i < total; i++) {
        if ($(inputs.get(i)).val() == id) {
            var own_idx = i; 
            break;
        }
    }
    return own_idx;
}

function load_film(id) {
    var idx = films_own_idx(id);
    // show description:
    $(".view-description-item").hide();
    var curr_item = ".view-description-item:eq(" + idx + ")";
    $(curr_item).show();
    var film = $(curr_item + " input:eq(0)").val();
    var film_hd = $(curr_item + " input:eq(1)").val();
    var still = $(curr_item + " input:eq(2)").val();

    jwplayer("view-player").setup({
        flashplayer: "/jwplayer/player.swf",
        file: film,
        height: 467,
        image: still,
        width: 830,
        plugins: "hd-1",
        wmode: "transparent",
        "hd.file": film_hd,
        "hd.state": "false",
        skin: "/jwplayer/modieus.swf"
    });
//    alert(idx);
}

// maybe make some of these vars global, controlled from php
var selector_scrolling = false;
var scroll_right = 1;
var scroll_left = -1;
var scroll_amount = 840;
function scroll_selector() {
    if (selector_scrolling) return;
    selector_scrolling = true;
    
    var curr_page = current_selector_page();
    var page_max = selector_pages_max(const_view_visible);

    var scroll_direction = "+";
    if ($(this).attr("id").indexOf("prev") != -1) {
        scroll_direction = "-";
        if (curr_page == 1) {
            $("#view-small").scrollTo("+=10", {duration:150}).scrollTo("-=10", {duration:150});
            setTimeout(function() {selector_scrolling = false;},350);
            return; // nothing to do
        }
        $("#view-selector-location img:eq(1)").attr("src","/images/selector/" + (curr_page - 1) + ".gif");
    } else {
        if (curr_page == page_max) {
            $("#view-small").scrollTo("-=10", {duration:150}).scrollTo("+=10", {duration:150});
            setTimeout(function() {selector_scrolling = false;},350);
            return; // nothing to do
        }
        $("#view-selector-location img:eq(1)").attr("src","/images/selector/" + (curr_page + 1) + ".gif");
    }


    $("#view-small").scrollTo(scroll_direction + "=" + scroll_amount, {duration:500});
    setTimeout(function() {selector_scrolling = false;},600);
}

function current_selector_page() {
    // const_view_visible is from php, but is not defined until we get here
    // ie, we cannot move this line outside the function.
    var scroll_visible = const_view_visible;
    var inputs = $(".view-small-item input");
    var total = inputs.size();
    var total_pages = Math.ceil(total/scroll_visible);
    var curr_page_src = $("#view-selector-location img:eq(1)").attr("src");
    var r = /(\d+)\.gif/i;
    var m_r = curr_page_src.match(r);
    return parseInt(m_r[1]);
}

function selector_pages_max() {
    var inputs = $(".view-small-item input");
    var total = inputs.size();
    var total_pages = Math.ceil(total/const_view_visible);
    return total_pages;
}

function view_selector_text(current) {
    var inputs = $(".view-small-item input");
    var total = inputs.size();
    var total_pages = selector_pages_max();
    for (var i = 0; i < total; i++) {
        if ($(inputs.get(i)).val() == current) {
            var own_idx = i; 
            break;
        }
    }

    // needs to add one to compensate for one-off
    var current_page = Math.ceil((own_idx+1) / const_view_visible);

    var html_page = "<img src=\"/images/selector/page.gif\">";
    var html_current = num_to_num_images(current_page);
    var html_divider = "<img src=\"/images/selector/divider.gif\">";
    var html_total = num_to_num_images(total_pages);
    
    $("#view-selector-location").html(html_page + html_current + html_divider + html_total);

}


function contains_url_fragment(url) {
    return url.lastIndexOf("#");
}

function extract_url_fragment(url) {
    if ((idx = contains_url_fragment(url)) > 0) {
        return url.substring(idx+1);
    } else {
        return undefined;
    }
}

function remove_url_fragment(url) {
    if ((idx = contains_url_fragment(url)) > 0) {
        url = url.substring(0, idx);
    }
    return url;
}

function num_to_num_images(num) {
    var str_num = "" + num;
    var str_res = "";
    for (var i = 0; i < str_num.length; i++) {
        var n = parseInt(str_num[i]);
        str_res += "<img src=\"/images/selector/" + n + ".gif\">";
    }
    return str_res;
}

