/* FX.Slide */
/* toggle window for the login section */
/* Works with mootools-release-1.2 */
/* more info at http://demos.mootools.net/Fx.Slide */
var default_block = "condiments";
var delivery_button_open = false;
var make_payment = false;
var editbasketopen = false;
var open = "condiments";

window.addEvent('domready', function(){

	$('login').setStyle('height','auto');
	if(env_topbar){
		var mySlide = new Fx.Slide('login');
	}else{
		var mySlide = new Fx.Slide('login').hide();  //starts the panel in closed state  		
	}
	if($('toggleLogin')){
	    $('toggleLogin').addEvent('click', function(e){
			SessionTopBar();
			e = new Event(e);
			mySlide.toggle();
			e.stop();
		});		
	}
	if ($('closeLogin')) {
		$('closeLogin').addEvent('click', function(e){
			SessionTopBar();
			e = new Event(e);
			mySlide.slideOut();
			e.stop();
		});
	}
});

function SessionTopBar(){
    var myRequest = new Request({
		method: 	'post',
		url: 		'/shoppingcart/savetopbar/',
    }).send();
}

function viewBasket(open_default){
	if(!clicked){
		clicked = true;
		openboxFrame(open_default);
	}
}

function openboxFrame(open_default){    
	var bgPlatform = new Element('div', {id: 'bgplatform'});
	getwinsize();
	bgPlatform.setStyles({
		"left":"0px",
		"top":"0px",
		"z-index":"900",
		"width": (myWidth - 15) + "px",
		"height": $(window).getScrollSize().y + "px",
		"display":"block",
		"margin":"0px",
		"padding":"0px",
		"background-color":"black",
		"position":"absolute",
	});
	bgPlatform.inject(document.body);

	var platformBox = new Element('div', {id: 'platformbox'});
	platformBox.setStyles({
		"left":((myWidth - 720) / 2) + "px",
		"top": GoToTop + "px",
		"z-index":"910",
		"width": "700px",
		"height": "400px",
		"display":"none",
		"margin":"0px",
		"padding":"0px",
		"background-color":"transparent",
		"position":"absolute",
	});
	platformBox.inject(document.body);

	var fadeFx = new Fx.Style(bgPlatform, 'opacity', {wait: false, duration: 500, onComplete:function(){
		floatLayer(0,GoToTop,'platformbox').Fm();
	    var myRequest = new Request({
			method: 	'get',
			url:		'/shoppingcart/popupbasket/',
			onComplete: function(request){
					platformBox.innerHTML = request;
					platformBox.setStyles({"display":"block"});
					var newfadeFx = new Fx.Style(platformBox, 'opacity', {wait: false, duration: 500, onComplete:function(){
						clicked = false;
						LoadSubmit(platformBox, bgPlatform, open_default);
					}}).set(0);
					newfadeFx.start(1);
			},
	    }).send();
	}}).set(0);
	fadeFx.start(0.8);

	bgPlatform.addEvent("click", function(){
		if(!clicked){
			clicked = true;
			var newfadeFx = new Fx.Style(platformBox, 'opacity', {wait: false, duration: 500, onComplete:function(){
				platformBox.destroy();
				var fadeFx = new Fx.Style(bgPlatform, 'opacity', {wait: false, duration: 500, onComplete:function(){
					bgPlatform.destroy();
					clicked = false;
				}}).set(0.8);
				fadeFx.start(0);
			}}).set(1);
			newfadeFx.start(0);
		}
	});
}

function LoadSubmit(platformBox, bgPlatform, open_default){
	open = open_default;
	$('formpopup').removeEvents("submit");
	$('formpopup').addEvent('submit', function(e) {
		e.stop();
		this.set('send', {onComplete: function(response) { 			
			platformBox.innerHTML = response;
			LoadSubmit(platformBox, bgPlatform, open);
			LoadBasket(open);
		}});
		this.send();
	})	
	$("popupclose").removeEvents("click");
	$("popupclose").addEvent("click", function(){
		if(!clicked){
			clicked = true;
			var newfadeFx = new Fx.Style(platformBox, 'opacity', {wait: false, duration: 500, onComplete:function(){
				platformBox.destroy();
				var fadeFx = new Fx.Style(bgPlatform, 'opacity', {wait: false, duration: 500, onComplete:function(){
					bgPlatform.destroy();
					clicked = false;
				}}).set(0.8);
				fadeFx.start(0);
			}}).set(1);
			newfadeFx.start(0);
		}
	});
	LoadBasket(open_default);

}

function resetMenu(){
	$("menu_condiments").setStyles({
		"color":"black", "background-image":"url(/static/img/bar_bg.png)",
	});
	$("box_condiments").setStyles({"display":"none",});
	$("menu_pastries").setStyles({
		"color":"black", "background-image":"url(/static/img/bar_bg.png)",
	});
	$("box_pastries").setStyles({"display":"none",});
	$("menu_giftboxes").setStyles({
		"color":"black", "background-image":"url(/static/img/bar_bg.png)",
	});
	$("box_giftboxes").setStyles({"display":"none",});
}

function LoadBasket(open_basket){
    balanceBasket();
	delivery_button_open = false;
	$("menu_condiments").removeEvents("click");
	$("menu_condiments").addEvent("click", function(){
		resetMenu();
		$("menu_condiments").setStyles({
			"color":"white", "background-image":"url(/static/img/footer_bg.png)",
		});
		$("box_condiments").setStyles({"display":"block",});
		open = "condiments";
	});
	$("menu_pastries").removeEvents("click");
	$("menu_pastries").addEvent("click", function(){
		resetMenu();
		$("menu_pastries").setStyles({
			"color":"white", "background-image":"url(/static/img/footer_bg.png)",
		});
		$("box_pastries").setStyles({"display":"block",});
		open = "pastries";
	});
	$("menu_giftboxes").addEvent("click", function(){
		resetMenu();
		$("menu_giftboxes").setStyles({
			"color":"white", "background-image":"url(/static/img/footer_bg.png)",
		});
		$("box_giftboxes").setStyles({"display":"block",});
		open = "giftboxes";
	});
	resetMenu();
	if(open_basket != "condiments" && open_basket != "giftboxes" && open_basket != "pastries"){
		open_basket = "condiments";
	}
    if(default_block == "giftboxes"){
	    open_basket = "giftboxes";
	}
    if(default_block == "pastries"){
	    open_basket = "pastries";
	}
	open = open_basket;
	$("menu_" + open_basket).setStyles({
		"color":"white", "background-image":"url(/static/img/footer_bg.png)",
	});
	$("box_" + open_basket).setStyles({"display":"block",});

	$("co_pastries_delivery_details_bar").removeEvents("click")
	$("co_pastries_delivery_details_bar").addEvent("click", function(){
	    if(delivery_button_open == false){
	        $("editDeliveryButton").style.display = "none";
	    	var fx = new Fx.Styles("co_pastries_delivery_details_bar", {duration:500, wait:true, onComplete: function(){
	            $("editDeliveryBlock").style.display = "block";
	    		var fadeFx = new Fx.Style("editDeliveryBlock", 'opacity', {wait: false, duration: 500, onComplete: function(){

					$('formDelivery').removeEvents("submit");
					$('formDelivery').addEvent('submit', function(e){
						$("save_pastries_country").value = $("sel_pastries_region").get("value");
						$("save_pastries_city").value = $("sel_pastries_city").get("value");
						$("save_pastries_suburb").value = $("sel_pastries_suburb").get("value");
						$("save_pastries_area").value = $("sel_pastries_area").get("value");
						e.stop();
						if ($("save_pastries_country").value != "" && $("save_pastries_city").value != "" && $("save_pastries_suburb").value != "" && $("save_pastries_area").value != "") {
							this.set('send', {
								onComplete: function(response){
									var fadeFx = new Fx.Style("pasteries_delivery", 'opacity', {
										wait: false,
										duration: 500,
										onComplete: function(){
											$("pasteries_delivery").style.display = "none";
											$("error_addproduct").style.display = "block";
											$("error_addproduct").innerHTML = '<p style="height:150px"></p><div id="success_addproduct" style="height: 85px;line-height: 20px;padding-top: 10px">You Have Successfully Selected A Major Center.<br/> You Can Now Add Pastries to Your Cart.</div>';
										}
									}).set(1);
									fadeFx.start(0);
									
									setTimeout(function(){
										parent.closeWindow();
									}, 4000);
								}
							});
							//Send the form.
							this.send();
						}
						else {
							alert("Please make sure you have selected a major area.");
						}
					});



	        		delivery_button_open = true;
	    		}}).set(0);
	    		fadeFx.start(1);
	    	}})
	    	fx.start({
	    		"height":"298px",
	    		"padding-top":"15px",
	    	});
	    }else{
	        
	    }
	});

}

function roundNumber(num,dec) {
    return num.toFixed(dec);
}

var PublicJson;

function balanceBasket(){
    var myRequest = new Request.JSON({
        url:    '/shoppingcart/json/basket/',
        onComplete: function(json){
            PublicJson = json;
            refreshBasket();
        }
    }).send();
}

function refreshBasket(){
    var json = PublicJson;
    var total_column_value = 0;
    var basket_cost = 0;
    var condiments_shipping_cost = 49.95;
    var pastries_shipping_cost = 59.95;
    var total_weight = 0;
    var subtotal_cost = 0;

    try{        
        for(var i = 0; i < json.condiments.length; i++) { 
            qty = $("bproduct_qty_" + json.condiments[i].lock_id).get("value");
            total_cv = qty * json.condiments[i].column_value;
            weight = json.condiments[i].weight;
            tw = qty * weight;

            total_column_value = total_column_value + total_cv;
            total_weight = total_weight + tw;

    //        alert(json.condiments[i].title + " | colval:" + json.condiments[i].column_value  + " | weight:" + weight + " | qty:" + qty + " | total colval:" + total_cv +  " | total weight:" + tw); 

            subtotal_cost = subtotal_cost + ((json.condiments[i].cost) * qty);
            $("bproduct_total_" + json.condiments[i].lock_id).innerHTML = "<center>R " + roundNumber(((json.condiments[i].cost) * qty), 2) + "</center>";
        }
        
        subboxes = 0;
        if(total_column_value > 12){
            total_weight = total_weight + 650;
            for(i=13;i <= total_column_value;i++){
                if((i%6) == 0) {
                    subboxes = subboxes + 1;
                }
            }
            if(subboxes != 0){
                for(i=0;i<=subboxes;i++){
                    total_weight = total_weight + 150;
                }
            }
        }else{
            total_weight = total_weight + 650;
        }

        max_val = Math.ceil((total_weight/1000)) * 1000;
        if(max_val< 5000){
            max_val = 5000;
        }
        perc = (total_weight/max_val * 100);
        $("condiments_pgbar_value").setStyles({"border": "2px solid #c1dd75", "background-image":"url(/static/img/err_green.png)"})
        $("condiments_pgbar_value").innerHTML = roundNumber((total_weight/1000),2) + "Kg (" + roundNumber(perc,2) + "%)";
        $("condiments_pgbar_value").style.width = perc + "%";
        $("pg_maxweight").innerHTML = "Fill Weight: <strong>" + ((max_val/1000)) + "Kg</strong>";

        if(subtotal_cost == 0){
            condiments_shipping_cost = 0;
        }else{
            if((max_val/1000) > 5){
                $("condiments_pgbar_value").setStyles({"border": "2px solid #9adffc", "background-image":"url(/static/img/err_progress_blue.jpg)"})            
                val = (max_val/1000);
                for(i = 5;i<val;i++){
                    condiments_shipping_cost = condiments_shipping_cost + 20.00;
                }
            }else{
                $("condiments_pgbar_value").setStyles({"border": "2px solid #c1dd75", "background-image":"url(/static/img/err_green.png)"})
            }
        }
        $("condiments_subtotal").innerHTML = "R " + roundNumber(subtotal_cost, 2);
        $("condiments_shipping_cost").innerHTML = "R " + roundNumber(condiments_shipping_cost, 2);
        $("condiments_total").innerHTML = "R " + roundNumber((subtotal_cost + condiments_shipping_cost), 2);
    }catch(e){}
    
    if(subtotal_cost == 0){
        condiments_shipping_cost = 0;
    }
    basket_cost = basket_cost + subtotal_cost + condiments_shipping_cost;

    try{
        subtotal_cost = 0;
        for(var i = 0; i < json.giftboxes.length; i++) { 
            qty = json.giftboxes[i].qty;
            subtotal_cost = subtotal_cost + ((json.giftboxes[i].cost) * qty);
        }
        $("giftboxes_total").value = roundNumber(subtotal_cost, 2);
        $("co_giftboxes_total").innerHTML = "R " + roundNumber(subtotal_cost, 2);
		if(roundNumber(subtotal_cost, 2) == 0.00){
			var myRequest = new Request({
				method: 	'get',
				url:		'/shoppingcart/popupbasket/',
				onComplete: function(request){
					$("platformbox").innerHTML = request;
					LoadSubmit($("platformbox"), $("platformbox"), open);
				},
			}).send();
		
		}
        basket_cost = basket_cost + subtotal_cost;
    }catch(e){}
    
    try{
        total_qty = 0;
        subtotal_cost = 0;
        for(var i = 0; i < json.pastries.length; i++) {
            qty = Number($("bproduct_qty_" + json.pastries[i].lock_id).get("value"));
            subtotal_cost = subtotal_cost + ((json.pastries[i].cost) * qty);
            $("bproduct_total_" + json.pastries[i].lock_id).innerHTML = "<center>R " + roundNumber(((json.pastries[i].cost) * qty), 2) + "</center>";
            total_qty = total_qty + qty;
        }
        boxes = "";
        t = 1;
        var total_shipping_cost = 0;
        for(i=0;i<total_qty;i++){
            if((i%4) == 0) {
                boxes = boxes + "<div class='pasteries_icebox'> Box " + t + " </div>";
                total_shipping_cost = total_shipping_cost + pastries_shipping_cost;
                t++;
            }
        }
        $("pgboxes").innerHTML = boxes;
        $("pastries_subtotal").innerHTML = "R " + roundNumber(subtotal_cost, 2);
        $("pastries_shipping_cost").innerHTML = "R " + roundNumber(total_shipping_cost, 2);
        $("pastries_total").innerHTML = "R " + roundNumber((subtotal_cost + total_shipping_cost), 2);
    }catch(e){}
    try{
        if(subtotal_cost == 0){
            total_shipping_cost = 0;
        }
        basket_cost = basket_cost + subtotal_cost + total_shipping_cost;

        $("basket_total").innerHTML = "R " + roundNumber(basket_cost,2);
    }catch(e){}
}


var giftbox_stage = 0;

function DeleteGiftbox(box_id, qty){
	$("save_giftbox_delete").value = "Y"; 
	$("save_giftbox_id").value = box_id;
	$("save_giftbox_qty").value = qty;
	$('formGiftbox').fireEvent("submit");
}

function openEditDelivery(box_id, qty){
	if (editbasketopen == false) {
		$("edit_giftbox_comment").setStyles({
			"display": "block",
			"height": "0px",
		})
	}else{
		$("edit_giftbox_comment").setStyles({
			"display": "block",
			"height": "300px",
		})		
	}
	if (view_title != "checkout") {
		$('formGiftbox').removeEvents("submit");
		$('formGiftbox').addEvent('submit', function(e) {
			this.set('send', {onComplete: function(response) { 
				$("checkout_giftbox_grid").innerHTML = response; 			
				if (view_title != "checkout") {
					$("grid_description").width = "50%";
					$("co_giftbox_label").width = "85%";
					$("co_giftbox_hidden_total").width = "25px";
					$("label_message_cog_makelong").setStyles({
						"display": "none"
					});
				}else{
					$("grid_description").width = "40%";
					$("co_giftbox_label").width = "85%";
					$("co_giftbox_hidden_total").width = "20px";
				}
	        	var fx = new Fx.Styles("edit_giftbox_comment", {duration:500, wait:true, onComplete: function(){
					balanceBasket();
					editbasketopen = false;
	        	}})
	        	fx.start({
	        		"height":"0px",
	        		"padding-top":"0px",
	        	});
			}});
			this.send();
		});
	}

	if(editbasketopen == false){
	    var myRequest = new Request({
			method: 	'post',
			url:		'/shoppingcart/checkout/edit/',
			onComplete: function(request){
				giftbox_stage = 0;
				$("edit_giftbox_comment").innerHTML = request;
				if(view_title == "checkout"){
					$("block_message_cog").style.display = "none";
					$("block_details_cog").style.display = "block";
					$("block_details_cog").style.width = "95%";
				}else{
					$("giftbox_msg_block").style.width = "350px";
					$("block_message_cog").style.display = "none";
					$("block_details_cog").style.display = "block";
					$("block_details_cog").style.width = "95%";
				}

				$("edit_giftbox_comment").style.display = "block";
				var fx = new Fx.Styles("edit_giftbox_comment", {duration:500, wait:true, onComplete: function(){
					editbasketopen = true;
				}});
	        	fx.start({
	        		"height":"300px",
	        		"padding-top":"15px",
	        	});
			}
	    }).send("box_id=" + box_id + "&qty_id=" + qty);
	}else{
			if(view_title != "checkout"){
				$("label_message_cog_makelong").setStyles({"display": "none"});
			}
		
		var fx = new Fx.Styles("edit_giftbox_comment", {duration:500, wait:true, onComplete: function(){
			editbasketopen = false;		
		}});
    	fx.start({
    		"height":"0px",
    		"padding-top":"0px",
    	});
	}
}

function setDeliveryFont(element){  

	var font_name = $$("input[name=delivery_font_cog]").map(function(e) { 
		var str = String(e.checked);
		var status = str.split(",");
		
		var val = String(e.value);
		var value = val.split(",");

		var new_value;
	
		for(i=0;i<value.length;i++){
			if(status[i] == "true"){
				new_value = String(value[i]);
			}
		}
		return new_value;
	 })
	
	$("save_giftbox_font").value = font_name;
	$("save_giftbox_contact").value = $("delivery_contact_cog").get("value");
	$("save_giftbox_address").value = $("delivery_address_cog").get("value"); 
	$("save_giftbox_province").value = $("delivery_province_cog").get("value"); 
	$("save_giftbox_city").value = $("delivery_city_cog").get("value"); 
	$("save_giftbox_suburb").value = $("delivery_suburb_cog").get("value");
	$("save_giftbox_area").value = $("delivery_area_cog").get("value");
	$("save_giftbox_postal").value = $("delivery_postal_cog").get("value");
	$("save_giftbox_message").value = $("delivery_message_cog").get("value");
	$("save_giftbox_nomessage").value = $("delivery_nomessage_cog").get("value");
}

function SubmitGiftbox(box_id, qty){
	if(giftbox_stage == 1){
        if ($("delivery_message_cog").get("value") != "") {
			$("save_giftbox_delete").value = "N"; 
			$("save_giftbox_contact").value = $("delivery_contact_cog").get("value");
			$("save_giftbox_address").value = $("delivery_address_cog").get("value"); 
			$("save_giftbox_province").value = $("delivery_province_cog").get("value"); 
			$("save_giftbox_city").value = $("delivery_city_cog").get("value"); 
			$("save_giftbox_suburb").value = $("delivery_suburb_cog").get("value");
			$("save_giftbox_area").value = $("delivery_area_cog").get("value");
			$("save_giftbox_postal").value = $("delivery_postal_cog").get("value");
			$("save_giftbox_message").value = $("delivery_message_cog").get("value");
			$("save_giftbox_nomessage").value = $("delivery_nomessage_cog").get("value");
			$("save_giftbox_id").value = box_id;
			$("save_giftbox_qty").value = qty;
			$('formGiftbox').fireEvent("submit");
		}else{
            $("label_message_cog").style.color = "red";
            $("label_message_cog").style.fontWeight = "bold";
		}
	}else{
        check_vals = ["contact", "address", "province","city", "suburb","area", "postal"];
        ok = true;
        var err_msg = "";
        var c=0;
        var err_lbl = [];
        for(i=0;i<check_vals.length;i++){
            if($("delivery_" + check_vals[i] + "_cog").get("value") == ""){
                ok = false;
                if(check_vals[i] == "contact"){
                    err_lbl[c] = "Name";
                }
                if(check_vals[i] == "address"){
                    err_lbl[c] = "Address";
                }
                if(check_vals[i] == "province"){
                    err_lbl[c] = "Province";
                }
                if(check_vals[i] == "city"){
                    err_lbl[c] = "City";
                }
                if(check_vals[i] == "suburb"){
                    err_lbl[c] = "Suburb";
                }
                if(check_vals[i] == "Area"){
                    err_lbl[c] = "Area";
                }
                if(check_vals[i] == "postal"){
                    err_lbl[c] = "Postal";
                }
                $("label_" + check_vals[i] + "_cog").style.color = "red";
                $("label_" + check_vals[i] + "_cog").style.fontWeight = "bold";
                c++;
            }else{
                $("label_" + check_vals[i] + "_cog").style.color = "black";
                $("label_" + check_vals[i] + "_cog").style.fontWeight = "bold";
            }
        }
        for(i=0;i<c;i++){
            if(i != (c-1)){
                if(c != 2){
                    err_msg += err_lbl[i] + ", ";
                }else{
                    err_msg += err_lbl[i] + " ";                                        
                }
            }else{
                if(c != 1){
                    err_msg += "and " + err_lbl[i] + " ";                                        
                }else{
                    err_msg += err_lbl[i] + " ";
                }
            }
        }
		if(c > 1){
			err_msg += "are ";
		}else{
			err_msg += "is ";
		}
		err_msg += "not filled in correctly.";
		                            
        if(ok == false){
            alert(err_msg);
        }
        if (ok == true) {
			giftbox_stage = 1;
			$("block_message_cog").style.display = "block";
			$("block_details_cog").style.display = "none";
			$("block_message_cog").setStyles({"width":"95%", "padding":"0px", "margin":"0px"});

			if(view_title != "checkout"){
				$("giftbox_msg_block").style.width = "350px";
				$("edit_giftbox_radiobuttons").style.padding = "0px";
				$("edit_giftbox_radiobuttons").style.margin = "0px";
				$("label_message_cog_makelong").setStyles({"width": "700px", "height":"30px", "position":"absolute"});
				$("label_message_cog").setStyles({ "height":"40px"});
				$("block_buttons").setStyles({ "width":"390px", "position":"relative", "top":"-50px"});				
			}

			$("giftbox_button_finish").setStyles({
				"background-image": "url(/static/img/button_done.png)",
				"width": "94px",
			});
		}
	}
}

function capitaliseFirstLetter(string){
    return string.charAt(0).toUpperCase() + string.slice(1);
}

function goHome(){
	self.location = "/";    
}

