/*
	Background Slides
	© 2011 borninteractive.com
	@author Makram
	
	- stretching
	- preloading
	- custom slides

*/

/*
    ScaleMode values: "fill" / "fit"
*/ 
var scaleMode = "fit"; 


jQuery.fx.interval = 50;
  
// PRELOADING ///////////////////////
var PRE_minimun_loaded_before_show = 2;

var PRE_buffer = [];          // populated at init then gets emptied as images load
var PRE_loaded_images = [];   // stores paths of loaded images
var PRE_total = 0;
var PRE_fakeinterval;

// These are set to `true` when the next or prev button is clicked but the image didn't load yet 
var BG_requested_index = null;


function PRE_init()
{
    try { tip_setDefault("loading, please wait..."); }catch(e){}
    
    // populate buffer array
    var no_active_vitrine = true;
    if(typeof active_vitrine_index != "undefined") {
        if(active_vitrine_index > 0) {
            var part_pre_active = BG_slides.slice(0, active_vitrine_index).join("|");
            var part_active_plus_three = BG_slides.slice(active_vitrine_index, active_vitrine_index+4).join("|");;
            var part_rest_slides = BG_slides.slice(active_vitrine_index+4, 1000).join("|");;
            var rearranged_parts = (part_active_plus_three +"|"+ part_pre_active +"|"+ part_rest_slides);
            PRE_buffer = rearranged_parts.split("|");
            no_active_vitrine = false;
        }
    } 
    
    if(no_active_vitrine) {
        for (var i=0; i < BG_slides.length; i++) {
              PRE_buffer.push(BG_slides[i]);
        }        
    }
    
    PRE_total = PRE_buffer.length;
    
    // start loading the first image
    PRE_startFakePreloaderProgress();
    PRE_next();
}
function PRE_loadImage(path)
{
    $("<img>").load(function() {
        PRE_loaded_images.push(path);
        PRE_setFakePreloaderProgressTo100();
        // check if this image is requested in a click
        if (BG_requested_index != null) {
            BG_showSlide(BG_requested_index);
        }
        PRE_next();
        $(this).remove();
    }).attr("src", path);
}
function PRE_pathIsLoaded(path)
{
    // checks if the requested path is added to the array of preloaded images
    for (var i=0; i < PRE_loaded_images.length; i++) {
        if(PRE_loaded_images[i].toLowerCase() == path.toLowerCase()) {
            return true;
        }
    }
    return false;
}
function PRE_next()
{
    // check if we can show the first BG
    if((PRE_total == PRE_loaded_images.length) || (PRE_loaded_images.length == PRE_minimun_loaded_before_show)) {
        BG_init();
    }
    //PRE_setLoaderProgress(PRE_loaded_images.length, PRE_total);
    if(PRE_buffer.length) {
        var img = PRE_buffer.shift();
        PRE_loadImage(img);              
    } else {
        // hide the progress bar if all images are loaded
        PRE_hidePreloader();
    }
}

function PRE_startFakePreloaderProgress()
{
    // show a slow, animated, fake loading progress
    var n = 0;
    $(".loading_bar").stop(true, true).show().fadeIn(10);
    $(".loading_strip").stop().css({width:0});
    var end_stop = 90 + Math.round(Math.random() * 7);  // fake number to show when progress reaches the end 
    if(typeof PRE_fakeinterval != "undefined") {
        clearInterval(PRE_fakeinterval);
    }
    PRE_fakeinterval = setInterval(function() {
        n += Math.random()*10;
        if(n > end_stop) n = end_stop;
        var pre = Math.round((n*100)/100);
        $(".loading_text").text(pre+"%");
        var max = $(".loading_bar").width();
        var pos = (pre * max) / 100;
        $(".loading_strip").css({opacity:.6});
        $(".loading_strip").stop().animate({width: Math.max(50, pos)+"px"}, 150);
        if(pre >= end_stop){
            clearInterval(PRE_fakeinterval);
        }
    }, 250);
}
function PRE_setFakePreloaderProgressTo100()
{
    // stop the fake progress
    clearInterval(PRE_fakeinterval);
    
    // slide to 100%
    var n = 100;
    var max = $(".loading_bar").width();
    var pre = Math.round((n*100)/100);
    $(".loading_text").text("100%");
    var pos = (pre * max) / 100;
    $(".loading_strip").stop().animate({width: pos+"px"}, 300);
}
function PRE_hidePreloader()
{
    setTimeout(function() {$(".loading_bar").fadeOut(300);}, 500);
}


function PRE_setLoaderProgress(n, total)
{
    var pre = Math.round((n*100)/total);
    if(typeof pre != "number") pre = 0;
    if(pre<100) {
        $(".loading_bar").show();
    }
    $(".loading_text").text(pre+"%");
    var max = $(".loading_bar").width();
    var pos = (pre * max) / 100;
    $(".loading_strip").css({opacity:.6});
    $(".loading_strip").animate({width: Math.max(50, pos)+"px"}, 200, function() {
        if(pre == 100){
            $(".loading_bar").fadeOut(300);
        }
    });
}

/////////////////////////////////////
// BG Images
var BG_slide_speed = isiPad() ? 350 : 1000;
var BG_disable_animation_on_IE = true;
var BG_min_window_width = 999;
var BG_min_window_height = 748;
      
var BG_slides_elems = [];
var BG_current_slide_index = -1;
var BG_total, BG_prev_slide;
var BG_area_w = 957;
var BG_area_h = 342;
var BG_is_moving = false;
var BG_inited = false;
var BG_easing = "";
var BG_last_clicked_arrow = null;

if(BG_disable_animation_on_IE) {
    if($.browser.msie) BG_slide_speed = 0;
}

function BG_resize()
{
    if(isiPad()) {
        BG_min_window_width = $(window).width();
        BG_min_window_height = $(window).height();
    }
    
    var resize = true;
    if(typeof BG_clipper_fixed != "undefined") {
        if(BG_clipper_fixed) resize = false;
    }
    
    if(resize) {
        BG_area_w = Math.max($(window).width(), BG_min_window_width);
        BG_area_h = Math.max($(window).height(), BG_min_window_height);
    }
    
    $("#BG_clipper").css({ width: BG_area_w, height: BG_area_h });
    
    $(".slidebox").each(function() {
        // container size
        $(this).css({ width: BG_area_w, height: BG_area_h });
        
        // image size and center
        var img = $(this).find("img");
        var w, h, scale_ratio;
        // reset image size to get original width and height
        img.css({width:"auto", height:"auto"});
        var ow = img.width();
        var oh = img.height();
        
        if(scaleMode == "fill") {
            // Fill screen
            if(ow > oh){
                // lanscape
                scale_ratio = ow / BG_area_w;
                w = BG_area_w;
                h = oh / scale_ratio;
                if(h < BG_area_h) {
                    scale_ratio = oh / BG_area_h;
                    h = BG_area_h;
                    w = ow / scale_ratio;
                }
            } else {
                // portrait
                scale_ratio = oh / BG_area_h;
                h = BG_area_h;
                w = ow / scale_ratio;
                if(w < BG_area_w) {
                    scale_ratio = ow / BG_area_w;
                    w = BG_area_w;
                    h = oh / scale_ratio;
                }
            }
        } else {
            // Fit to screen
            scale_ratio = oh / BG_area_h;
            h = BG_area_h;
            w = ow / scale_ratio;
            //console.log(h);
            if(w > BG_area_w) {
                 console.log(w);
                 scale_ratio = ow / BG_area_w;
                w = BG_area_w;
                h = oh / scale_ratio;
            }
            
        }
        
        
        var diff_w = (BG_area_w - w)/2;
        var diff_h = (BG_area_h - h)/2;
       if(scaleMode == "fill") {
           // center image
           img.css({ width: w+"px", height: h+"px", left:diff_w+"px", top:diff_h+"px" });
       } else {
           // keep on left top
           img.css({ width: w + "px", height: h + "px"});
       }
        
    });
}

function BG_showSlide (index) 
{
    if(BG_is_moving) return;  // do nothing if another slide is moving into position
    var path = BG_slides[index];
    // check if the requested slide is already loaded...
    if(!PRE_pathIsLoaded(path)){
        // ...not loaded yet => set the waiting var (it'll be called later when the image loads)
        BG_requested_index = index;
        PRE_startFakePreloaderProgress();
        return;
    }
    PRE_hidePreloader();
    //PRE_setFakePreloaderProgressTo100();
    
    setTimeout(function() {BG_unHighlightArrows();}, 300);
    
    var slide = $("<div>").addClass("slidebox");
    var img = $("<img>").attr("src", path);
    img.appendTo(slide);
    slide.appendTo("#BG_clipper");
    
    if($(".slidebox").length > 1) {
        BG_is_moving = true;
        // add a slide on the side and move it either 
        // from left or from right based on previous index
        var from_left = (index > BG_current_slide_index);
        if(typeof BG_flip_arrows != "undefined") {
            if(BG_flip_arrows) {
                from_left = !from_left;
            }
        }
        if(from_left) {
             slide.css({ left:-BG_area_w+"px" });
             $(BG_prev_slide).animate({ left:BG_area_w+"px" }, BG_slide_speed, BG_easing, function() {
                 $(this).remove();
                 BG_is_moving = false;
             });
        } else {
            slide.css({ left:BG_area_w+"px" });
            $(BG_prev_slide).animate({ left:-BG_area_w+"px" }, BG_slide_speed, BG_easing, function() {
                $(this).remove();
                BG_is_moving = false;
            });
        }
    }
    BG_resize();
    setTimeout(BG_resize, 100); // resize again to make sure the current image is resized properly (bug fix)
              
    slide.animate({ left:"0px" }, BG_slide_speed, BG_easing, function() {
        $(this).animate({top:"0px"}, 0);
    });
    BG_prev_slide = slide;
    BG_current_slide_index = index;
    BG_requested_index = null;    
    
    // nav buttons
    $(".slide_prev_btn").show();
    $(".slide_next_btn").show();
    if(BG_current_slide_index == 0) {
        $(".slide_prev_btn").hide();
    }
    if(BG_current_slide_index == BG_total-1) {
        $(".slide_next_btn").hide();
    }
    
    /*
        show carousel item
    */
    $("#mycarousel li").hide();
    $("#mycarousel li:eq("+BG_current_slide_index+")").show();
    
    // handle white arrows
    if(typeof white_arrows_on_first_slide != "undefined") {
        if(white_arrows_on_first_slide){ 
            if(BG_current_slide_index == 0) {
                setTimeout(function() {
                    $(".slide_prev_btn img").attr("src", "images/next_white.png");
                    $(".slide_next_btn img").attr("src", "images/prev_white.png");                    
                    if(typeof BG_flip_arrows != "undefined") {
                        if(BG_flip_arrows) {
                            $(".slide_prev_btn img").attr("src", "images/prev_white.png");
                            $(".slide_next_btn img").attr("src", "images/next_white.png");
                        }
                    }
                }, 750);
            } else {                                  
                setTimeout(function() {
                    $(".slide_prev_btn img").attr("src", "images/next.png");
                    $(".slide_next_btn img").attr("src", "images/prev.png");
                    if(typeof BG_flip_arrows != "undefined") {
                        if(BG_flip_arrows) {
                            $(".slide_prev_btn img").attr("src", "images/prev.png");
                            $(".slide_next_btn img").attr("src", "images/next.png");
                        }
                    }
                }, 200);
            }
        }
    }
}
function BG_prevSlide(event)
{
    BG_unHighlightArrows();
    BG_highlightArrows(event.target);
    
    if(BG_current_slide_index > 0) {
        BG_showSlide(BG_current_slide_index - 1);
    }
}
function BG_nextSlide(event) 
{
    BG_unHighlightArrows();
    BG_highlightArrows(event.target);
    
    if(BG_current_slide_index < BG_total-1) {
        BG_showSlide(BG_current_slide_index + 1);
    }
}
     
function BG_unHighlightArrows()
{
    $(BG_last_clicked_arrow).stop().css({
        opacity:1
    });
}
function BG_highlightArrows(arrow) 
{
    $(arrow).css({
        opacity:.4
    });
    
    BG_last_clicked_arrow = arrow;
}

        
// init
function BG_init()
{
    if(BG_inited) return;
    
    BG_total = BG_slides.length;
    if(typeof active_vitrine_index != "undefined") {
        BG_showSlide(active_vitrine_index);
    } else {
        BG_showSlide(0);
    }
    
    BG_inited = true;
    
    $(window).resize(function() {
        BG_resize();
    });
    $(window).bind('focus', function(){
        BG_resize();
    });
    
    // show the vitrine nav controls and info
    $(".vitrine-nav").show();
	hidePreloadingCovers("slides");
	//$('#loader').hide();
	
    try { tip_setDefault(""); }catch(e){}
    
    // add swipe events
    if(isiPad()) {
        try {
            $(".topMenuContainer").touchwipe({
                wipeLeft: function() { BG_prevSlide({target:$(".slide_prev_btn")}); },
                wipeRight: function() { BG_nextSlide({target:$(".slide_next_btn")}); }
            });
            $("body").touchwipe({
                wipeLeft: function() { BG_prevSlide({target:$(".slide_prev_btn")}); },
                wipeRight: function() { BG_nextSlide({target:$(".slide_next_btn")}); }
            });
            
        } catch(e){}
    }
}


// start preloading images once the page loads
$(window).load(function()
{
    // add IDs and events to the next/prev arrows
    
    if(typeof BG_flip_arrows != "undefined") {
        if(BG_flip_arrows) {
            $(".prevBtn").addClass("slide_prev_btn");
            $(".nextBtn").addClass("slide_next_btn");
        }
    } else {
        $(".prevBtn").addClass("slide_next_btn");
        $(".nextBtn").addClass("slide_prev_btn");
        
    }
    
    $(".slide_prev_btn").click(BG_prevSlide);
    $(".slide_next_btn").click(BG_nextSlide);
    
    // 
    PRE_init();
});
$(document).ready(function() {
    showPreloadingCovers("slides");
});



