
function goOrder()
{
    var pass = false;
    if (Model.page == "order" && ($('#order').length))
        pass = true;
    writeHash("order");
    var params = "";
    if (Model.city)
        params = "city="+Model.city;
    if (!pass)  {
        $("#wrapper").load("order.php?" + Math.random()+" #order", function()   {
            if (!Model.atem().page)
                loadInfoPage('#infotext');//$('#infotext').load(Model.atem().pageUrl + " #middle-model-shortstory");
            else {
                $(Model.atem().page).find('.cross').hide();
                $(Model.atem().page).appendTo($('#infotext').empty());
            }

            $('#interiorImage').attr('src', Model.atem().prefix + Model.atem().interior[Model.atem().activeInteriorIdx].img);

        });
    }
    $("#content").load("order.php?combo=1&" + Math.random()+"", params, function(){
            $('select').change(function(){
                var val = $('select').val();
                Model.city = val;
                goOrder();
            });
        });

    $('#wrapper').css('padding-top', '0px');
    $('#wrapper').css('background', 'none');
    middleHeight = 670; // 70px is height of steper
    $("#middle").css("height", middleHeight + "px");
    $("#wrapper").css("height", middleHeight - 70 + "px");
    showSteper();
}

function loadInfoPage(selector)
{
    $(selector).load(Model.atem().pageUrl + " #middle-model-shortstory","", function(text) {
        //$('<img src="' + Model.atem().prefix + Model.atem().infoImg+'" />').appendTo($(text).find("#middle-model-shortstory")[0]);
        Model.atem().page = $(text).find("#middle-model-shortstory")[0];
        $(Model.atem().page).find('a.moroes').attr('target',"_blank");
        //$(Model.atem().page).css("margin-top", "-35px");    
        $('<img id="infoImage" src="' + Model.atem().prefix + Model.atem().infoImg+'" />').appendTo(Model.atem().page/*$('.infotext').find("#middle-model-shortstory")*/);
        $('<div class="cross"/>').appendTo(Model.atem().page);
        if (selector == "#infotext")
            $(Model.atem().page).find('.cross').hide();
        else
            $(Model.atem().page).find('.cross').show();
        
        $(Model.atem().page).appendTo($(selector).empty());
    });
}

function goInterior()
{
    writeHash("interior");
    $("#wrapper").load("interior.htm?" + Math.random(), "", function()   {
        if (!Model.atem().page)
            loadInfoPage('.infotext');
        else {
            $(Model.atem().page).find('.cross').show();
            $(Model.atem().page).appendTo($('.infotext').empty());
        }
        $('#content').load(Model.atem().pageUrl + " #holytablet");
        var buttons = $('img[name^="interiorVariant"]');
        var atem = Model.atem();
        if (atem.activeInteriorIdx == null)   atem.activeInteriorIdx = 0;
        $('img[name^="interiorVariant"]').each(function(idx,el)   {
            var name = $(el).attr('name');
            var idx = name.substr(name.length-1, 1);
            $(el).attr('src', atem.prefix + atem.interior[idx].buttonImg);
        });
        $('img[name^="interiorVariant"]').click(function(e){
            var name = $(e.currentTarget ).attr('name');
            var idx = name.substr(name.length-1, 1);
            atem.activeInteriorIdx = idx;
            writeHash();
            $('img[name="interiorImage"]').attr('src', atem.prefix + atem.interior[idx].img);//"images/interior/interior01v" + idx + "_r1_c2.gif");
        });
        $('img[name="interiorImage"]').attr('src', atem.prefix + atem.interior[atem.activeInteriorIdx].img);
    	$('.ibutton').css({
                left: atem.ix + 'px',
    			top: atem.iy + 'px'
    		});
    	var infoWidth = $('.infotext').width();
    	var btnHeight = $('.ibutton').height();
    	
    	$('.infotext').css({
                left: (atem.ix - infoWidth) + 'px',
    			top: (atem.iy + btnHeight / 2)  + 'px'
    		});
    	
        $('.ibutton').click(function()  {
            $('.infotext').slideDown(200);
        });
        $('.infotext').click(function() {
            $('.infotext').slideUp(200);
        });
    });
    middleHeight = 670; // 70px is height of steper
    $('#wrapper').css('padding-top', '0px');
    $('#wrapper').css('background', 'none');
    $("#middle").css("height", middleHeight + "px");
    $("#wrapper").css("height", middleHeight - 70 + "px");
    showSteper();
}


function goMain()
{
    writeHash("main");
    //var idx = 0;
    //if ()
    //window.location.hash = "#main:" + Model.activeItemKey;

    $("#wrapper").load("main.htm #main", "", function()   {
        initMain();
        $('#content').load("main.htm #mainContent");
    });
    $('#wrapper').css('padding-top', '40px');
    $('#wrapper').css('background', 'url(./images/MESOL.jpg) no-repeat');
	
    $("#middle").css("height", 403 + "px");
    $("#wrapper").css("height", 410 + "px");
    showSteper();
}

function goResult()
{
window.print();
}

function shuffle(array) {
	for (var j,x,i=array.length; i; j = parseInt(Math.random()*i), x = array[--i], array[i] = array[j], array[j] = x);
	return true;
    // return arr.sort(function() {return 0.5 - Math.random()});
}


function initMain()  {
    var html = $('#demo-frame div.wrapper').html();
    var imageCaption = $('#imageCaption');
    $('#demo-frame div.wrapper').parent().append(html).end().remove();
    $sliderCtrl = $('#slider');
    $coverflowCtrl = $('#coverflow');
    //alert('cover' + $coverflowCtrl.length);
    // add images
    $coverflowCtrl.empty();
    var defaultItem  = 0;
    var html = "";
    var arr = [];
	Model.videoIdx = 0;
    for (var i = 0, c = Model.items.length; i < c; i++) {
        var item = Model[Model.items[i]];
        if (!item) continue;
        for (var j = 0, cj = 1; j < cj; j++)    {
            //alert(item.interior.length);
            if (item.interior[j].img) {
                //$coverflowCtrl.append($('<img src="' + item.prefix + item.interior[j].img +'" data-item="'+item.id+'" data-idx="' + defaultItem + '" data-interiorIdx="' + j + '"/>'));
                arr.push('<img src="' + item.prefix + item.interior[j].img +'" data-item="'+item.id+'" data-idx="" data-interiorIdx="' + j + '"/>');
                //html += '<img src="' + item.prefix + item.interior[j].img +'" data-item="'+item.id+'" data-idx="' + defaultItem + '" data-interiorIdx="' + j + '"></img>';
                //alert($coverflowCtrl.find('img').length);
                defaultItem ++;
			
            }
			if (item.video && !Model.videoIdx) Model.videoIdx = i;
        }
    }
    
    //shuffle(arr);
    for (var i = 0, c = arr.length; i < c; i ++)    {
        arr[i] = arr[i].replace('data-idx=""', 'data-idx="' + i + '"');
        $coverflowCtrl.append(arr[i]);
    }
    
    //$coverflowCtrl.innerHTML = html;
    $coverflowImages = $coverflowCtrl.find('img');
    $sliderVertical  = $("#slider-vertical");

    //app defaults
    defaultItem = defaultItem / 2 ;
    if (!Model.atem())    {
        Model.activeItemKey =   $('img[data-idx="' + Math.floor(defaultItem) + '"]').attr("data-item");
        //Model.atem().activeInteriorIdx =   "0";//$('img[data-idx="' + Math.floor(defaultItem) + '"]').attr("data-interiorIdx");
    }
    Model.atem().activeInteriorIdx =  0;
    var listContent = "";


    //Set the default image index.   

    // menu
    $coverFlowMenu = $("#coverflow_menu");
    $coverFlowMenuPlaceholder = $("#coverflow_menu_placeholder");
    $coverFlowMenuTop = 400;
    $coverFlowMenuTopShift = 40;
    $coverFlowMenuTimeout = 2000;
    $coverFlowMenu.css('top', $coverFlowMenuTop + 'px'); 
    $coverFlowMenu.load("menu.htm", "", function()    {
        $('#Menu_left').click(function(){
            skipLeft();
        });
        $('#Menu_right').click(function(){
            skipRight();
        });
        $('#Menu_interior').click(function(){
            //goInterior();
			skipTo(0);	
            // slide to first interior
        });
        $('#Menu_video').click(function(){
			skipTo(Model.videoIdx);	
        });
    });

    window.coverflowMenuTimeout = setTimeout(function() {
        $coverFlowMenu.animate({
            "margin-top": 40
        }, 1000);
    }, $coverFlowMenuTimeout * 2);
    $("#coverflow_menu, #coverflow_menu_placeholder").mouseover(function(){
        clearTimeout(window.coverflowMenuTimeout);
        $("#coverflow_menu").stop();
        //$("#coverflow_menu").css('top', 360);
        $("#coverflow_menu").animate({
            "margin-top": 0
        }, {
            step: function(a, fx)   {
                //console.log(a);
            }
        });
    });
        $('#coverflow_menu').mouseout(function(){
            clearTimeout(window.coverflowMenuTimeout);
            window.coverflowMenuTimeout = setTimeout(function() {
                $("#coverflow_menu").animate({
                   "margin-top": 40
                    }, 1000);
            }, $coverFlowMenuTimeout);
        });
    $coverflowCtrl.coverflow({
        item: defaultItem,
        duration:1200,
        select: function(event, sky) 
        {
            skipTo(sky.value);

        },
        choose: coverflowClick
            
    });
    //getSliderIdx();
    
    //var idx = $('img[data-item="' + Model.activeItemKey + '"][data-interiorIdx="'+Model.atem().activeInteriorIdx+'"]').attr("data-idx");
    var idx = $('img[data-item="' + Model.activeItemKey + '"][data-interiorIdx="'+Model.atem().activeInteriorIdx+'"]').attr("data-idx");
    skipTo(idx);

    //Assign click event for coverflow images 
    //$('body').delegate('.coverflowItem','click', function(){
    //    skipTo($(this).data('itemlink'));
    //});
    $("#scroll-pane").css('overflow','hidden');
    $(".coverflowItem.ui-selected").live('click',coverflowClick);
}

function coverflowClick()   {
    if (!Model.atem().video)	{
        goInterior();
	}
    else	{
        goVideo();
	}
}

function goVideo()
{
    window.location.href = "video.php?video=" + Model.atem().id;
	
}

function loadSteper()
{
    $steper = $("#steper");
    $steper.load("Steper.htm","", function(){
        showSteper();
        $("#stepLeft").click(
            goMain
            );
    });
}

function showSteper(step)   {
    var step = 0;
    if ((Model.page == null) ||(Model.page == "main") || (Model.page == ""))
        step = 0;
    else if (Model.page == "interior") 
        step = 1;
    else if (Model.page == "order")
        step = 2;
    //else step = 3;

    show = false;
    if ((step> 0)&&(step<3))
        show = true;
    if (show)   {
        $("#steper").find("#stepLeft").attr("src", "images/steper/Steper_r1_c1_" + (step + 1) + ".gif");
        $("#steper").find("#stepRight").attr("src", "images/steper/Steper_r1_c3_" + (step + 1) + ".gif");
        $("#steper").find("#stepLabel").attr("src", "images/steper/Steper_r1_c2_" + (step + 1) + ".gif");
        $("#stepRight").unbind('click');
        if (Model.page == "interior")
            $("#stepRight").click(goOrder);
        else
            $("#stepRight").click(goResult);

    }
    if (!show)  {
        $("#steper").hide();
    }
    else    {
        $("#steper").show();
    }
}

//Set the default item to display on load.
//Correct indexing
	   
  
		
//Initialize CoverFlow
//Skip to an item in the CoverFlow	
function skipTo($itemNumber)
{  
    Model.activeItemKey = $('img[data-idx="' + $itemNumber + '"]').attr("data-item");
    Model.atem().activeInteriorIdx = $('img[data-idx="' + $itemNumber + '"]').attr("data-interiorIdx");
    $sliderCtrl.slider( "option", "value", $itemNumber);
    $coverflowCtrl.coverflow('select', $itemNumber, true);
    $('.coverflowItem').removeClass('ui-selected');
    $('.coverflowItem:eq(' + ($itemNumber) +')').addClass('ui-selected');

}


function skipLeft()
{
    $current = $coverflowCtrl.data().coverflow.current
    if($current > 0){ 
        $current--;
        skipTo($current);
    }
}

function skipRight()
{
    $current = $coverflowCtrl.data().coverflow.current
    if($current < $('#coverflow > *').length-1){ 
        $current++;
        skipTo($current);
    }	     
}


function writeHash( pageName)
{
    if (!pageName)
        pageName = Model.page;
    else
        Model.page = pageName;
    var interiorIdx = 0;
    if (Model.atem() && Model.atem().activeInteriorIdx)
        interiorIdx = Model.atem().activeInteriorIdx;
    
    h = '#' + pageName + ":" +Model.activeItemKey + ":" + interiorIdx;
    window.location.hash = h;
    
}

function parseHash(page, data)
{
    var h = window.location.hash.substring(1);
    var parts = h.split(":");
    page = parts[0];
    var data, subdata;
    Model.page = page;
    if (parts.length > 1)
        data = parts[1];
    if (parts.length > 2)
        subdata = parts[2];
        if (data)   {
            Model.activeItemKey = data;
            if (!Model.atem())
                Model.activeItemKey  = Model.items[0];
        }
        if (subdata)    {
            if (Model.atem())
                Model.atem().activeInteriorIdx = subdata;
        }
    
    if (page == "interior") {
        goInterior();
    }
    if (page == "order")    {
        goOrder();
        
    }
    else  if ((page == "main") || (page== null)||(page=="")){
        goMain();
    }
}

$(document).ready(function() {
    //alert('body' + $('body').length);
    
    if (window.mainInited) return;
    window.mainInited = 1;
	var a = window.location.href;
	var b = a.replace(/index.html/,'');
	if (b != a) {
		window.location.href = b;	
	}
	b = a.replace(/index.php/,'');
	if (b != a) {
		window.location.href = b;	
	}

    loadSteper();
    //cache core component references
    // load stper

    //Handle keyboard events
    $(document).keydown(function(e){
		
        //$current = $sliderCtrl.slider('value');
        if (window.lastKeyTimeStamp && (e.timeStamp == window.lastKeyTimeStamp))
            return;
        window.lastKeyTimeStamp = e.timeStamp;		
        switch(e.keyCode){   
            case 37:
                skipLeft();
                break;
            case 39:
                skipRight();
                break;
        }
		   
    });
		
		
		
		

    //change the main div to overflow-hidden as we can use the slider now
	
    //calculate the height that the scrollbar handle should be
    //    var difference = $("#sortable").height()-$("#scroll-pane").height();//eg it's 200px longer 
    //    var proportion = difference / $("#sortable").height();//eg 200px/500px
    //    var handleHeight = Math.round((1-proportion)*$("#scroll-pane").height());//set the proportional height



	
    //mousewheel support
	
    $(document).mousewheel(function(event, delta){
	
        var speed = 1;
        var sliderVal = $sliderCtrl.slider("value");//read current value of the slider
        var coverflowItem = 0;
        var cflowlength = $('#coverflow > *').length-1;

       
        //check the deltas to find out if the user has scrolled up or down 
        if(delta > 0 && sliderVal > 0){
            sliderVal -=1;
        }else{
            if(delta < 0 && sliderVal < cflowlength){
                sliderVal +=1;
            }
          
        }
     
        var leftValue = -((100-sliderVal)*difference/100);//calculate the content top from the slider position
		
        if (leftValue>0) leftValue = 0;//stop the content scrolling down too much
        if (Math.abs(leftValue)>difference) leftValue = (-1)*difference;//stop the content scrolling up beyond point desired
		
        coverflowItem = Math.floor(sliderVal);
        skipTo(coverflowItem);
	
        event.preventDefault();//stop any default behaviour
    });
    /*
    $('a.moroes').live('click',function(e)  {
       e.stopImmediatePropagation();
       alert(5);
    });
    */
    parseHash();
});


