/****************************************
    Website Coded by Gelo Factory LLC
           All Rights Reserved
           (c)  Copyright 2008
         http://gelofactory.com/
****************************************/

$(function() {
    /*
     * Image Preloader
     */

    var pi = new Array();
    var pio = new Array();

    function queuePreloadImg(arg) {
        pi.push(arg);
    }

    function preloadImgs(to) {
        setTimeout(function() {
            pio = new Array();
            $.each(pi, function(pii, pie) {
                pio.push(new Image());
                pio[pii].src = pie;
            });
            pi = new Array();
        }, to);
    }

    queuePreloadImg("./_img/loading_zoom.gif");
    queuePreloadImg("./_img/loading_denim.gif");
    queuePreloadImg("./_img/spacer.gif");
    preloadImgs(0);

	/*
	 * Denim
	 */

    if ($('body.denim').length) {
        // constants
        var anim_sp = "normal";
        var anim_sp_slow = "slow";
        var anim_sp_fast = "fast";
        var anim_stagger = 500;
        var anim_lock = false;
        var zoom_enable_to = 1000;
        var zoom_buf = 4;
        var fit_width = 130;
        var img_base = "";
        var img_spacer = "_img/spacer.gif";
        var img_loading = "_img/loading_denim.gif";
        var img_zoom_loading = "_img/loading_zoom.gif";
        var wash_thumb_shift = 88;
        var wash_thumb_dims = [78, 127];
        var wash_max = 3;
        var zoom_w = 680;
        var fit_w = 110;
        var fit_h = 178;
        var img_w = 280;
        var img_h = 466;
        var img_buf = 4;

        // vars
        var denim_data = null;
        var cur_season = null;
        var cur_cat_o = null;
        var cur_fit_o = null;
        var cur_wash_o = null;

        $.getJSON('_js/json/denim.json', {}, function(data) {
            denim_data = data;
            buildSubnav(null, buildDenimSeason);
        });

        // Build the subnav for denim
        var buildSubnav = function(season, cb) {
            $.each(denim_data, function(i, e) {
                $('#seasons_nav').empty();

                var fs_h2 = "";
                var se_lis = [];

                if (e['seasons'].length) {
                    if (season == null) season = e['seasons'][0]['id'];
                    cur_season = season;

                    $.each(e['seasons'], function(si, se) {
                        var cat_ul = null;
                        if (se['id'] == cur_season) {
                            var cat_lis = [];
                            cur_cat_o = null;
                            $.each(se['categories'], function(ci, ce) {
                                if (ce['fits'].length) {
                                    if (cur_cat_o == null) cur_cat_o = ce;
                                    var cat_a = $.create("a", {href: "javascript:void(0);", id: "cat"+ce['id']}, [htmlentities(ce['title'])]);
                                    if (ce['id'] == cur_cat_o['id']) $(cat_a).addClass("selected");
                                    var cat_li = $.create("li", {id: "cat_li"+ce['id']}, [cat_a]);
                                    cat_lis.push(cat_li);
                                }
                            });
                            if (cat_lis.length) cat_ul = $.create("ul", {}, cat_lis);
                        }

                        var se_a = $.create("a", {href: "javascript:void(0);", id: "seas"+se['id']}, [se['title']+" "+se['year']]);
                        $(se_a).addClass("seas");
                        if (se['id'] == season) $(se_a).addClass("selected");
                        var se_ch = [se_a];
                        if (cat_ul) se_ch.push(cat_ul);
                        se_lis.push($.create("li", {}, se_ch));
                    });

                    // build seasons
                    $('#seasons_nav').hide();
                    $('#seasons_nav').append(se_lis);

                    // seasons click events
                    if (e['seasons'].length > 1) {
                        $('#seasons_nav .seas').click(function() {
                            if (!anim_lock) {
                                anim_lock = true;
                                var seas = $(this).attr('id').substr(4);
                                hideDenimSeason(function() {
                                    anim_lock = false;
                                    buildSubnav(seas, function() { buildDenimSeason(); });
                                });
                            }
                        });
                    }

                    // categories click events
                    $('#seasons_nav a').click(function() {
                        if (!anim_lock) {
                            anim_lock = true;
                            var cat_id = this.id.substr(3);
                            hideCurDenimCategory(function() {
                                anim_lock = false;
                                $.each(denim_data, function(i, e) {
                                    if (e['seasons'].length) {
                                        $.each(e['seasons'], function(si, se) {
                                            if (se['id'] == cur_season) {
                                                cur_cat_o = null;
                                                $.each(se['categories'], function(ci, ce) {
                                                    if (ce['id'] == cat_id) cur_cat_o = ce;
                                                });
                                            }
                                        });
                                    }
                                });
                                buildCurDenimCategory();
                            });
                        }
                    });

                    // show nav + execute callback
                    if ($.browser.msie) {
                        $('#seasons_nav').show();
                        cb();
                    } else {
                        $('#seasons_nav').fadeIn(anim_sp, function() { cb(); });
                    }
                }
            });
        };

        var buildDenimSeason = function() {
            buildCurDenimCategory();
        };

        var buildCurDenimCategory = function() {
            if (!anim_lock) {
                anim_lock = true;

                $('#thumbs_list').empty().width(0).css("left", "0px");
                $('.thumbnav').empty();
                $('#full_img_wrap img').attr('src', img_spacer);
                $('#full_img_wrap img').attr('src', img_loading);
                $('#full_wash').empty();
                $("#thumb_description h3, #thumb_description p").empty();
                $("#thumbs span").css("left", "0px");

                $("#cat_li"+cur_cat_o['id']).addClass("selected");

                var fits_len = cur_cat_o['fits'].length;
                var fits_row_max = Math.ceil(fits_len / 2);

                $("#item_grid").empty().width(fits_row_max * fit_width).fadeIn(anim_sp, function() {
                    anim_lock = false;
                });

                // reorder fits by reversing the order of the entries in each
                // row because of the "float: right" style on .item divs
                if ((typeof(cur_cat_o['fits_reordered']) == "undefined") || !cur_cat_o['fits_reordered']) {
                    var new_fits = [];
                    for (var i = 0; i < fits_row_max; i++) new_fits[i] = cur_cat_o['fits'][fits_row_max - i - 1];
                    for (var i = fits_row_max; i < fits_len; i++) new_fits[i] = cur_cat_o['fits'][fits_len - i - 1 + fits_row_max];
                    cur_cat_o['fits'] = new_fits;
                    cur_cat_o['fits_reordered'] = true;
                }

                $.each(cur_cat_o['fits'], function(fi, fe) {
                    var item_div_a_img = $.create("img", {src: fe['image_path'], width: fit_w, height: fit_h, alt: ""}, []);
                    var item_div_a_p1 = $.create("p", {"class": "fit_title"}, [fe['title']]);
                    var item_div_a_p2 = $.create("p", {}, [fe['description']]);
                    var item_div_a = $.create("a", {href: "javascript:void(0);", id: "fit"+fe['id']}, [item_div_a_img, item_div_a_p1, item_div_a_p2]);
                    var item_div = $.create("div", {"class": "item"}, [item_div_a]);
                    $("#item_grid").append(item_div);
                });

                $("#item_grid .item a").click(function() {
                    if (!anim_lock) {
                        anim_lock = true;
                        var fit_id = this.id.substr(3);
                        $.each(cur_cat_o['fits'], function(fi, fe) {
                            if (fe['id'] == fit_id) cur_fit_o = fe;
                        });
                        if (cur_fit_o) {
                            hideCurDenimGrid(function() {
                                buildCurDenimFit();
                            });
                        }
                    }
                });
            }
        };

        var hideCurDenimGrid = function(cb) {
            $('#item_grid').fadeOut(anim_sp, function() { cb(); });
        };

        var hideCurDenimCategory = function(cb) {
            //$("#seasons_nav li").removeClass("selected");
            $("#cat_li"+cur_cat_o['id']+", #cat_li"+cur_cat_o['id']+" a").removeClass("selected");
            if ($('#thumb_description').css("display") == "block") {
                $('#full, #thumbs').fadeOut(anim_sp);
                $('#thumb_description').fadeOut(anim_sp, function() { cb(); });
            } else if ($('#item_grid').css("display") == "block") {
                $('#item_grid').fadeOut(anim_sp, function() { cb(); });
            }
        };

        var buildCurDenimFit = function() {
            $("#thumb_description h3").html(cur_fit_o['title']);
            $("#thumb_description p").html(cur_fit_o['description']);
            if (cur_fit_o['washes'].length) {
                var wash_thumb_left_pos = ((wash_max - cur_fit_o['washes'].length) * (wash_thumb_shift / 2));
                $("#thumbs ul")
                    .empty()
                    .css("left", wash_thumb_left_pos+"px")
                    .width(cur_fit_o['washes'].length * wash_thumb_shift);
                $("#thumbs span").css("left", wash_thumb_left_pos+"px");
                cur_wash_o = cur_fit_o['washes'][0];
                $.each(cur_fit_o['washes'], function(wi, we) {
                    var ul_li_a_img = $.create("img", {src: img_base + we['image_path_thumb'], width: wash_thumb_dims[0], height: wash_thumb_dims[1], alt: ""}, []);
                    var ul_li_a = $.create("a", {href: "javascript:void(0);", id: "d_lst_wash"+we['id']}, [ul_li_a_img]);
                    var ul_li = $.create("li", {}, [ul_li_a]);
                    $("#thumbs ul").append(ul_li);
                    var thumbnav_a = $.create("a", {href: "javascript:void(0);", id: "d_nav_wash"+we['id']}, [we['wash']]);
                    $(".thumbnav").append(thumbnav_a);
                });
                $("#thumbs_list li a, .thumbnav a").click(function() {
                    if (!anim_lock) {
                        anim_lock = true;
                        var cur_wash_id = this.id.substr(10);
                        if (cur_wash_o['id'] != cur_wash_id) {
                            $.each(cur_fit_o['washes'], function(wi, we) {
                                if (we['id'] == cur_wash_id) cur_wash_o = we;
                            });
                            hideCurWash(buildCurWash);
                        } else {
                            anim_lock = false;
                        }
                    }
                });
                buildCurWash();
                $("#full, #thumbs").fadeIn(anim_sp);
            }
            $("#thumb_description").fadeIn(anim_sp, function() { anim_lock = false; });
        };

        var buildCurWash = function() {
            var afterMoveFrame = function() {
                $("#full_img_wrap img").attr("src", img_base + cur_wash_o['image_path']);
                $("#full_wash").html(cur_wash_o['wash']);
                $("#d_nav_wash"+cur_wash_o['id']).addClass("selected").css("cursor", "default");
                $('#full_img_wrap').fadeIn(anim_sp);
                $('#full_wash').fadeIn(anim_sp, function() {
                    anim_lock = false;
                });
                // zoom
                $('#full .zoom a').unbind('click').click(function() { zoomImage(); });
                $('#full .back a').unbind('click').click(function() { unZoomImage(); });
            };
            var cur_wash_i = null;
            $.each(cur_fit_o['washes'], function(wi, we) {
                if (we['id'] == cur_wash_o['id']) cur_wash_i = wi;
            });
            var frame_left = (cur_wash_i != null) ? (parseInt($("#thumbs ul").css("left"), 10) + (cur_wash_i * wash_thumb_shift) + "px") : null;
            if ($("#thumbs span").css("left") == frame_left) {
                afterMoveFrame();
            } else {
                $('#thumbs span').animate({left: parseInt(frame_left, 10)}, anim_sp_slow, "linear", function() { afterMoveFrame(); });
            }
        };

        var hideCurWash = function(cb) {
            $(".thumbnav a").removeClass("selected").css("cursor", "pointer");
            $('#full_img_wrap').fadeOut(anim_sp, function() {
                $('#full_img_wrap img').attr('src', img_spacer);
                $('#full_img_wrap img').attr('src', img_loading);
            });
            $('#full_wash').fadeOut(anim_sp, function() { $('#full_wash').empty(); });
            cb();
        };

        var hideDenimSeason = function(cb) {
            $('#item_grid, #thumb_description, #thumbs, #full').fadeOut(anim_sp);
            $('#seasons_nav').fadeOut(anim_sp, function() { cb(); });
        };

        var zoomImage = function() {
            if (!anim_lock) {
                anim_lock = true;
                $('#seasons_nav, #aside, #thumb_description, #thumbs, #full_wash, #full .zoom').fadeOut(anim_sp_fast);
                $('#full_img_wrap').fadeOut(anim_sp_fast, function() {
                    $('#full_img_wrap img').attr('src', img_spacer);
                    $('#full_img_wrap img').attr('src', img_zoom_loading);
                    $('#full').animate({width: zoom_w+img_buf}, anim_sp_slow, "linear", function() {
                        $("#full_img_wrap").css("width", zoom_w+"px");
                        $('#full_img_wrap img').removeAttr('width').removeAttr('height');
                        $('#full_img_wrap img').attr('src', img_base + cur_wash_o['zoom_image_path']);
                        $("#full_img_wrap img").css("margin-left", "0px").css("margin-top", "0px");
                        $('#full_img_wrap, #full_wash').fadeIn(anim_sp);
                        $('#full .back').fadeIn(anim_sp, function() {
                            anim_lock = false;
                            enableZoom();
                        });
                    });
                });
            }
        };

        var unZoomImage = function() {
            if (!anim_lock) {
                anim_lock = true;
                disableZoom(false);
                $('#full_img_wrap, #full_wash').fadeOut(anim_sp_fast);
                $('#full .back').fadeOut(anim_sp_fast, function() {
                    disableZoom();
                    $("#full_img_wrap").css("width", img_w+"px");
                    $('#full_img_wrap img').attr('width', img_w).attr('height', img_h);
                    $('#full_img_wrap img').attr('src', img_spacer);
                    $('#full_img_wrap img').attr('src', img_loading);
                    $('#full').animate({width: img_w+img_buf}, anim_sp_slow, "linear", function() {
                        disableZoom();
                        $('#full_img_wrap img').attr('src', img_base + cur_wash_o['image_path']);
                        $('#seasons_nav, #aside, #thumb_description, #thumbs, #full_wash, #full .zoom').fadeIn(anim_sp);
                        $('#full_img_wrap').fadeIn(anim_sp, function() {
                            disableZoom();
                            anim_lock = false;
                        });
                    });
                });
            }
        };

        var enableZoom = function() {
            setTimeout(function() {
                var panImage = function() {
                    if ((parseInt(cur_wash_o['zoom_image_w'], 10) > 0) && (parseInt(cur_wash_o['zoom_image_h'], 10) > 0)) {
                        $("#full_img_wrap").mousemove(function(e) {
                            var fiwo = $("#full_img_wrap").offset();
                            var fiwx = (e.pageX - fiwo.left);
                            var fiwy = (e.pageY - fiwo.top);
                            if (fiwx < zoom_buf) fiwx = 0;
                            if (fiwx > (zoom_w - zoom_buf)) fiwx = zoom_w;
                            if (fiwy < zoom_buf) fiwy = 0;
                            if (fiwy > (img_h - zoom_buf)) fiwy = img_h;
                            var fiwl = parseInt(((fiwx/zoom_w)*(cur_wash_o['zoom_image_w']-zoom_w)), 10);
                            var fiwt = parseInt(((fiwy/img_h)*(cur_wash_o['zoom_image_h']-img_h)), 10);
                            $('#full_img_wrap img').css("margin-left", (0-fiwl)+"px").css("margin-top", (0-fiwt)+"px");
                        });
                    }
                };
                panImage();
                $("#full_img_wrap").mouseover(function() { panImage(); });
                $("#full_img_wrap").mouseout(function() { $("#full_img_wrap").unbind('mousemove'); });
                $("#full_img_wrap").css("cursor", "move");
            }, zoom_enable_to);
        };

        var disableZoom = function(repos) {
            repos = (typeof(repos) == "undefined") ? true : repos;
            $("#full_img_wrap").unbind('mouseover').unbind('mousemove').css("cursor", "default");
            if (repos) {
                $('#full_img_wrap img').css("margin-left", "0px");
                $('#full_img_wrap img').css("margin-top", "0px");
            }
        };

        var htmlentities = function(str) {
            var ta = document.createElement("textarea");
            ta.innerHTML = str;
            return ta.value;
        };
    }
});
