
// Define the global variables
var pathArray = document.location.pathname.split( '/' );
var baseUrl = pathArray[1];
var selectedItems=new Array();
var selectedItemVolume=0;
var allUnits	= Array();
var citysel;
var isbulk		= 0;
function decByThirty(value){
    return value - (value * (3/10));
}
function calculateUnit(volume, units) {
    if (units[0] === null || units[0] === undefined) {
        return false;
    }
	
    // We assumed that the units are sorted asc by volume
    if(volume > 0 && volume < decByThirty(units[0].volume)){
        if(isbulk>0 && units[0].volume < 400){
            for(var j = 1; j<units.length; j++){
                if(units[j].volume >= 400)
                    return units[j];
            }
        } else {
            return units[0];
        }
    }
	 
    if(units.length == 1){
        if(volume < decByThirty(units[0].volume))
            return  units[0];
        else
            return false;
    } else {
	 
        for(var i = 0; i< (units.length - 1); i++){
            if(volume >= decByThirty(units[i].volume) && i == units.length-1)
                return false;
            if(volume >= decByThirty(units[i].volume) && volume < decByThirty(units[i+1].volume) ){
                if(isbulk>0 && units[i+1].volume < 400){
				 		
                    for(var j = i+2; j< (units.length - 1); j++){
                        if(units[j].volume >= 400)
                            return units[j];
                    }
                } else {
                    return units[i + 1];
                } 
            }
        }
    }
	 
    return false;
}

function getUnits(citysel){
    $.getJSON('/'+ baseUrl +'/getunits',{
        'city':citysel
    }, function(data) {
        if(data.units === undefined || data.units === null || data.units.length == 0){
            alert('Please select a valid city');
            $("#selectcity").val('');
            return false;
        }
        allUnits    =	data.units;
        allFeatures =   data.features;
        displayFeatures(allFeatures);
        update_total();
    });
}
function displayFeatures(features){
    if(features.length < 1 ){
        $("#facilityFeatures").hide();
        return;
    }
    $('#featureTable').find('tr').remove();
    $.each(features, function(key,value){
        $('#featureTable').append($("<tr><td width='18'><img src='/img/booking/tick.jpeg' width='26' height='28' /></td><td width='176'>"+value+"</td></tr>"));
    });
    $("#facilityFeatures").hide().fadeIn(400);
	
}
function getAllItems(){
    $.getJSON('/'+ baseUrl +'/getitems',null, function(data) {
        if(data === undefined || data === null || data.length == 0){
            alert('Please select a valid item');
            return false;
        }
        if(data.status	==	1){
            allItems	=	data.products;
        }
    });
}
$(document).ready(function(){
	
    //Don't display the container div unless the document is ready
    $("#readyToLoad").show();
	
    $('a.processing').hide();
    $('#clearbutton').hide();
    $("#facilityFeatures").hide();
    //Min browser requirements
    if ($.browser.msie && $.browser.version.substr(0,1)<7) {
        document.location.href='/'+ baseUrl +'/browsererror';
    }
    if ($("#selectcity option").size() == 2 && $("#selectcity option:selected").length){
        $('#selectcity option:eq(1)').attr('selected', 'selected');
        citysel=parseInt($('#selectcity').val());
        getUnits(citysel);
    }

    //Retrieve all items
    getAllItems();
	
    $("ul.tabs").tabs("div.panes > div");
    $("#dragYourItems").show();
    $('.processing').click(function() { 
        $.blockUI({ 
            message: $('#loadingcontainer'),
            css: { 
                top:  ($(window).height() - 250) /2 + 'px',
                left: ($(window).width() - 250) /2 + 'px',
                border: 'none',
                padding: '15px',
                width:'250px',
                backgroundColor: '#FFFFFF',
                '-webkit-border-radius': '10px',
                '-moz-border-radius': '10px',
                opacity: .7,
                color: '#ffffff'
            }
        });
    setTimeout($.unblockUI, 1000);
    }); 
// Get session variables
$.getJSON('/'+ baseUrl +'/getses',null, function(data) {
    if(data.isactive	==	1){
			
        citysel	=	data.location;
        $("#selectcity").val(citysel);
			
        getUnits(citysel);
			
        var sessionItems =	data.items;
			
        $.each(sessionItems, function(key,value){
				
            var smallicon	=	'<div id="'+value.id+'item" class="itembox">';
            smallicon		+=  '<div style="text-align:right;width:60px;"><a href="#" onclick="remove('+value.id+');return false;" class="remove"><img src="/img/booking/delete.png"  border="0"/></a></div>';
            smallicon		+=	'<div id="resim"><img src="/img/booking/products/'+value.iconimage+'" height="60" width="60" /></div><div class="yazi">';
            smallicon		+=	'<span style="font-size:10px">&nbsp;&nbsp;Qty:</span><select class="qty" name="'+value.id+'_cnt" id="'+value.id+'_cnt" onchange="change('+value.id+');"><option value="1">1</option>';
            smallicon		+=  '<option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option><option value="100">More</option></select></div></div>';

            $(smallicon).appendTo($('#item-list'));
            if(value.cnt >= 10) {
                $('#'+value.id+'_cnt').append($("<option></option>").
                    attr("value",value.cnt).
                    text(value.cnt));
            }
            $('#'+value.id+'_cnt').val(value.cnt);
				
            selectedItems.push({
                id:value.id,
                cnt:value.cnt,
                itemVolume:value.itemVolume,
                isbulk:value.isbulk
                });
				
            isbulk	   = isbulk + parseInt(value.isbulk)*value.cnt;
            selectedItemVolume += parseInt(value.cnt*value.itemVolume);
				
        });
			
			
		
        $(".itembox").draggable({
				
            containment: 'document',
            opacity: 0.6,
            revert: 'invalid',
            helper: 'clone',
            zIndex: 102

        });
				
    }
			
});
	

$(".product img").draggable({
	
    containment: 'document',
    opacity: 0.6,
    revert: 'invalid',
    helper: 'clone',
    zIndex: 100
	
});
	
$("#clearbutton").click(function(){
		
    removeAll();
});
	
$("#selectcity").change(function(){
    $("#facilityFeatures").hide();
		
    citysel=parseInt($(this).val());
    if(!(citysel > 0)){
        alert('Please select a city');
        $('a.processing').hide();
        return false;
    }
		
		
    getUnits(citysel);
});

$("div.content.drop-here").droppable({
	
    drop:
    function(e, ui)
    {
        if($(ui.draggable).attr('class') != "pngfix ui-draggable")
            return false;
        var para = $(ui.draggable).attr('id');
        var param= parseInt(para);
						
        if(param==undefined)
            return false;
						
        if($.browser.msie && $.browser.version=='6.0')
        {
            param = $(ui.draggable).attr('style').match(/src=\"([^\"]+)\"/);
            param = param[1];
        }
						
        addlist(param);
    }
	
});
$("div.content.drag-desired").droppable({
		
    drop:
    function(e, ui)
    {
        if($(ui.draggable).attr('class') != "itembox ui-draggable")
            return false;
        var par = $(ui.draggable).attr('id');
        param	=	parseInt(par);

        if(!isNaN(param) && param>0){
            remove(param);
        }
        return false;
    }

});

});


function addlist(param)
{

    if(citysel === null || citysel === undefined){
        alert('Please select your city first');
        return false;
    }
    var msg	=	getItemById(param, allItems);
	
    if(!msg) {
        alert('This item can not be found');
        return false;
    }
		
    var check=false;
    var cnt = false;

    for(var i=0; i<selectedItems.length;i++)
    {
        if(selectedItems[i].id==msg.id)
        {
            check=true;
            cnt=selectedItems[i].cnt;
            break;
        }
    }
	
    if(!cnt) {
		
        var smallicon	=	'<div id="'+msg.id+'item" class="itembox">';
        smallicon		+=  '<div style="text-align:right;width:60px;"><a href="#" onclick="remove('+msg.id+');return false;" class="remove"><img src="/img/booking/delete.png"  border="0"/></a></div>';
        smallicon		+=	'<div><img src="/img/booking/products/'+msg.iconimage+'" height="60" width="60" /></div><div class="yazi">';
        smallicon		+=	'<span style="font-size:10px">&nbsp;&nbsp;Qty:</span><select class="qty" name="'+msg.id+'_cnt" id="'+msg.id+'_cnt" onchange="change('+msg.id+');"><option value="1">1</option>';
        smallicon		+=  '<option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option><option value="100">More</option></select></div></div>';
		
        //alert(smallicon);
		
        $(smallicon).prependTo($('#item-list'));
    }
    if(!check)
    {
        selectedItems.push({
            id:msg.id,
            cnt:1,
            itemVolume:msg.itemVolume,
            isbulk:msg.isbulk
            });
    }
    else
    {
        if(cnt>=10) return false;
		
        selectedItems[i].cnt++;
		
        $('#'+msg.id+'_cnt').val(selectedItems[i].cnt);
    }
	
    selectedItemVolume+=parseInt(msg.itemVolume);
    isbulk	   = isbulk + parseInt(msg.isbulk);
    $(".itembox").draggable({
		
        containment: 'document',
        opacity: 0.6,
        revert: 'invalid',
        helper: 'clone',
        zIndex: 101
		
    });
    update_total();

}

function findpos(id)
{
    for(var i=0; i<selectedItems.length;i++)
    {
        if(selectedItems[i].id==id)
            return i;
    }
	
    return false;
}

function remove(id)
{
    var i=findpos(id);

    selectedItemVolume-=selectedItems[i].itemVolume * selectedItems[i].cnt;
	
    if(selectedItems[i].isbulk	==	1)
        isbulk	=	isbulk	- selectedItems[i].cnt ;
	
	
    selectedItems[i].cnt = 0;
    $('#'+id+'item').show().fadeOut(500);
    setTimeout(function() {
        $('#'+id+'item').remove()
    }, 100); 

    update_total();

}
function removeAll(){
    selectedItemVolume = 0;
    selectedItems = Array();
    $("#item-list").html('');
    isbulk	   = 0;
    update_total();
	
}
function IsNumeric(sText) {

    var ValidChars = "0123456789.";
    var IsNumber=true;
    var Char;

	 
    for (i = 0; i < sText.length && IsNumber == true; i++)
    {
        Char = sText.charAt(i);
        if (ValidChars.indexOf(Char) == -1)
        {
            IsNumber = false;
        }
    }

    return IsNumber;
	   
}

function change(id)
{
    var i=findpos(id);
    var n;
    if(parseInt($('#'+id+'_cnt').val()) == 100) {
		
        if(!$("#dialog-form_"+id).length){
            var e = $("<div class='hiddia' id='dialog-form_"+id+"' title='Please Enter Quantity'><form><fieldset><label for='name'>Quantity</label><input type='text' name='exqty_"+id+"' id='exqty_"+id+"' class='text ui-widget-content ui-corner-all' /></fieldset></form></div>");
            $('body').append(e);
        }
		
		
        $("#dialog-form_"+id).dialog({
            autoOpen: false,
            height: 150,
            width: 350,
            modal: true,
            closeOnEscape: false,
            buttons: {
                'Enter the quantity': function() {
                    var bValid = true;
                    $("#exqty_"+id).removeClass('ui-state-error');

                    bValid = bValid && IsNumeric($("#exqty_"+id).val());
					
                    if (bValid) {
                        n	=	parseInt($("#exqty_"+id).val());
                        if(isNaN(n) || n>500){
                            alert('There is a problem with the quantity, it can not exceed 500. Please try again');
                            remove(id);
                            update_total();
                            $(this).dialog('close');
                            return false;
                        }
                        $('#'+id+'_cnt').append($("<option></option>").
                            attr("value",n).
                            text(n));
                        $('#'+id+'_cnt').val(n);
                        selectedItemVolume+=(n-selectedItems[i].cnt)*selectedItems[i].itemVolume;
						
                        selectedItems[i].cnt=n;
                        update_total();
                        $(this).dialog('close');
                    } else {
                        alert('This is not a number');
                        remove(id);
                        update_total();
                        $(this).dialog('close');
                        return false;
                    }
                },
                Cancel: function() {
                    remove(id);
                    update_total();
                    $(this).dialog('close');
                    return false;
					
                }
            },
            close: function() {
                $("#exqty_"+id).val('').removeClass('ui-state-error');
                return false;
            }
        });
	

        $('#dialog-form_'+id).dialog('open');
		
        $('#dialog-form_'+id).find('input').keypress(function(e) {
            if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
                $(this).parent().parent().parent().parent().find('.ui-dialog-buttonpane').find('button:first').click(); /* Assuming the first one is the action button */
                return false;
            }
        });
		
    } else {
        var n =	parseInt($('#'+id+'_cnt').val());
	
	
        selectedItemVolume+=(n-selectedItems[i].cnt)*selectedItems[i].itemVolume;
        if(selectedItems[i].isbulk == 1){
            isbulk += (n-selectedItems[i].cnt)*1 ;
        }
        selectedItems[i].cnt=n;
        update_total();
    }
}

function update_total()
{
	
    if(selectedItemVolume && selectedItemVolume>0 )
    {
        $("#dragYourItems").hide();
		
        var sunit = "";
		
        $('#totalvolume').html(selectedItemVolume);
        $('#totalvolumein').val(selectedItemVolume);
		
        var calculatedUnit	=	calculateUnit(selectedItemVolume, allUnits);
        if(!calculatedUnit){
            sunit	=	'Please call us for quote';
            $('#suggestedunit').html(sunit);
            $('#totalprice').html('');
            $('a.processing').hide();
            $('#clearbutton').hide();
        } else {
            sunit = calculatedUnit.name;
           // rent  = calculatedUnit.price;
            $('#suggestedunit').html(sunit);
            $('#totalprice').html('');
            $('a.processing').show();
            $('#clearbutton').show();
            var unitPrice = 0;
            var j=0;
            for(var i = 0; i<allUnits.length; i++){
                var u = allUnits[i];
                if((u.name == calculatedUnit.name) && (unitPrice == 0 || (u.price < unitPrice)) ){
                    unitPrice = u.price;
                }
            }
            $('#totalprice').append('$' + unitPrice + ' ');
        }

    }
    else
    {
        $('#suggestedunit').html('Drag an item');
        $('#totalprice').html('$ 0' );
        $('#totalvolume').html('0');
        $("#dragYourItems").show();
        $('a.processing').hide();
        $('#clearbutton').hide();
    }
}



function getItemById(id, items){
    for (var i = 0; i< items.length; i++){
        if(items[i].id == id)
            return items[i];
    }
    return false;
	 
}
