/* Jquery version 1.1.3.1 
-- Book clubs javascript  
-- Author: Dan Eastwell (daneastwell at gmail dot com) 


// Existing child_id 423761

*/
// Global constants
 var navName="#open_order_summary"; // The whole nav
 var jsOnClass="external-nav-on";
 
 var navHandler="#external-nav h2"; // The thing you click on to open the nav
 var navOffClass="closed";
 
 var navList="form#open_order_summary ul.orders-sumary"; // The element that contains the nav items
 
 var navLevelId="form#open_order_summary ul li ul"; // The element that contains the second level items
 
 var handleNames=new Array("#open_by_class h3", "#open_order_summary h4"); // Things you can click in the nav to make them open
 var addedClass="highlighted";


$(document).ready(function() { 
	doPopup();
	labelInput("club_search_words");
	labelInput("club_search_words2");
	fetchItem();
	addItem();
	removeItem();
	
	$('#order_form' | '#open_order_summary').click( function( event ) {
	 var $target = $(event.target);
	 if( $target.is('img.increment') ) return change( 1 );
	 if( $target.is('img.decrement') ) return change( -1 );

	 function change( by ) {
		var $qty = $target.parent('td').find('input[type=text]');
		var n = +$qty.val() + by;
		if( n >= 0 ) $qty.val( n );
		return false;
	 }
	});
	
	$(".default-js").addClass("hidden");
	$(".summarytable tr:even").addClass("odd"); 
	$("ul.orders-sumary tr:even").addClass("odd"); 
	prepareNav();
	
	
});

function doPopup() {
	  
	  if (!document.getElementsByTagName) return false; 
	  
	  var links = document.getElementsByTagName("a");
	  for (var i=0; i < links.length; i++) {
			if (links[i].getAttribute("rel") == "popup") {
				links[i].onclick = function(){	
					
					popUp(this.getAttribute("href"));
					return false;
				}
			}
		}
}

function popUp(winURL){
	window.open(winURL, "popup", "width=420,height=480");
}

/*function revealInput{
	
}*/

// Remove text in search box on click/focus
function labelInput(theSearchBox) {
    var labelText = $("label[for='" + theSearchBox + "']").text();
    var labelBox;
    if (labelBox = document.getElementById(theSearchBox)) {
        labelBox.value = labelText;
        labelBox.onfocus = function () {this.value = "";};
        labelBox.onblur = function () {if (this.value == "") {this.value = labelText;}};
    }
}

/* Ajax fetch item */
// Fetches JSON object from the server and populates the item title on the page

function fetchItem(){
	$("select#offer_id").change(function(){
		$("input#sbc_seq").val("");
		$("div#added-item").html("");
	});
	$("input#sbc_seq").change(function(){
	    $.getJSON("get-title",{sbc_seq: $(this).val(), offer_id: $("select#offer_id").val() }, function(j){
		    if(j.return_code == "OK") {
		        output_title = '<p>' + j.title + '</p>';
		        $("input#sbc_seq").removeClass("open_order_summary_error");

		    }else{
			if((j.return_code == "ERROR")){
				output_title = '<p>' + j.error + '</p>';
			}else{
				output_title = "<p>We couldn't fetch the title for this item number.</p>";
			}
		        $("input#sbc_seq").addClass("open_order_summary_error");
   		    }
		    $("div#added-item").html(output_title);
	    });
	})
}

/* Ajax add item */
// TESTING: addItem.js, addNewChildItem.js, addNewClassItem.js, addNewOfferItem.js
	
function addItem(){

  $("form#add_item").submit(function(){

	$.ajax({
		type: "POST",
		url: "add-item",
		data: {		offer_id: $(this.offer_id).val(), 
				sbc_seq: $(this.sbc_seq).val(), 
				paid_qty: $(this.paid_qty).val(),
				free_qty: $(this.free_qty).val(), 
				class_name: $(this.class_name).val(), 
				child_name: $(this.child_name).val() 
				},
		dataType : "json",
		success: function(added_item){
			$("#form-message").hide();
			if(added_item.return_code == "ERROR"){
				output_title = '<p>' + added_item.error + '</p>';
	  	        	$("div#added-item").html(output_title);
                                if(added_item.error == "You must enter a quantity"){
                                        $("input#paid_qty").addClass("open_order_summary_error");            
                                }else{
                                        $("input#sbc_seq").addClass("open_order_summary_error");
                                }
			}
			if(added_item.return_code == "OK"){
                            $("div#added-item").html("");    
                            $("input#paid_qty").removeClass("open_order_summary_error");	
			    var existing_row = document.getElementById(added_item.order_detail_id);
			    if (existing_row) {
			    	var existing_paid = $("input[name='paid_qty']", existing_row);
			    	var existing_free = $("input[name='free_qty']", existing_row);
                                var paid_qty = Number(added_item.paid_qty);
                                var free_qty = Number(added_item.free_qty);
                                if(isNaN(paid_qty)) {paid_qty=0;}
                                if(isNaN(free_qty)) {free_qty=0;}
				existing_paid[0].value = Number(existing_paid[0].value) + paid_qty; 
				existing_free[0].value = Number(existing_free[0].value) + free_qty; 
			    }else{
				var new_row = constructNewRow(added_item.item_title, added_item.paid_qty, added_item.free_qty, added_item.price, added_item.child_id, added_item.order_detail_id, added_item.currency);

				if(added_item.child_id){
					var tableID = 'summary_child_id:' + added_item.child_id
				}else{
					var tableID = 'summary_offer_id:' + added_item.offer_id
                                }
				var table_for_offer_child = document.getElementById(tableID)
				
				if(!table_for_offer_child){ 
					createNewOrderItemTable(added_item.offer_id,added_item.offer_name,added_item.class_id,added_item.class_name,added_item.child_id,added_item.child_name); 
				        table_for_offer_child = document.getElementById(tableID);
				}else{
					var last_ix = table_for_offer_child.rows.length - 1
					var last_row  = table_for_offer_child.rows[last_ix]
					if (! $(last_row).hasClass("odd")) {
						$(new_row).addClass("odd");
                                        }						
                                }
				
				$(table_for_offer_child).append(new_row);
				$(table_for_offer_child).parent("li").addClass("current");	
				temp = $(table_for_offer_child).prev();
				var headingHandle = new Array("#open_by_class h3:not(.prepared)", "#open_order_summary h4:not(.prepared)");
				addEventHandlers(headingHandle, 0, "selected");

			    }
				
			    increment_totals(added_item.offer_id, added_item.price, added_item.paid_qty, added_item.free_qty, added_item.child_id, added_item.class_id, added_item.currency)
			    $("#form-message").show();
			    $("#form-message-text").fadeOut(200);			    
			    $("#form-message-text").queue(function () {
				$(this).text('Added "' + added_item.title + '" ' + ( added_item.class_name ? " to " + added_item.child_name + " in " + added_item.class_name : "")).fadeIn(200);
				$(this).dequeue();
			    });
		            document.add_item.sbc_seq.value = '';	
        		    document.add_item.paid_qty.value = '1';	
        		    document.add_item.free_qty.value = '';	
        		    document.add_item.sbc_seq.focus();	
			}
		},
		error: function(msg){
			if(msg.status == 0){
				alert("uninitialised ajax: " + msg.responseText);
			}
		}
	});
	
	return false;
  });





}

// do this later
function removeItem(){
  $("form#open_order_summary td.removexxx input").click(function(){

	$.ajax({
		type: "POST",
		url: "removeItem.js",
		data: {	remove_item: $(this).attr("id") },
		dataType : "json",
		success: function(removed_item){
			if(removed_item.return_code == "OK"){	
				$("#" + removed_item.removed_item).parent().parent("tr").fadeOut("slow", function(){
				   $(this).remove();
				 });
			}
		},
		error: function(msg){
			if(msg.status == 0){
				alert("uninitialised ajax: " + msg.responseText);
			}
		}
	});
	return false;
  });
}

function constructNewRow(item_title,paid_qty,free_qty,price,child_id, order_detail_id, currency){
	// create a <tr> with the relevant information in it. (returns a tr element)
	
	
	
	var row = document.createElement("tr");
	row.id = order_detail_id
	var cell_title = document.createElement("td");
	cell_title.className = "title";
	var cell_qty = document.createElement("td");
	$(cell_qty).addClass("qty_plus_minus")
	var cell_free_qty = document.createElement("td");
	$(cell_free_qty).addClass("qty_plus_minus")
	var cell_price = document.createElement("td");
	var cell_remove = document.createElement("td");
	var line_value = 0;
	if (paid_qty){
		line_value = paid_qty * price
	}
	cell_title.innerHTML = item_title;
	
	cell_qty.innerHTML = "<input type='text' class='text' name='paid_qty' value='" + paid_qty + "' size='3' />";
	cell_qty.innerHTML += "<img src='/images/button_minus.gif' alt='-' class=\"decrement\" /><img src='/images/button_plus.gif' alt='+' class=\"increment\" />";
	cell_qty.innerHTML += "<input type='hidden' name='order_detail_id' value='" + order_detail_id + "' />";

	cell_free_qty.innerHTML =	"<input type='text' class='text' name='free_qty' value='" + free_qty + "' size='3' />";
        cell_free_qty.innerHTML += "<input type='hidden' name='child_id' value='" + child_id + "' />";
	cell_free_qty.innerHTML += "<img src='/images/button_minus.gif' alt='-' class=\"decrement\" /><img src='/images/button_plus.gif' alt='+' class=\"increment\" />";
	cell_price.innerHTML = "<span class='price'>" + prettyCurrency(line_value, currency) + "</span>";
	cell_price.className = 'currency';
	cell_remove.innerHTML = "<input type='image' tabindex='-1' src='/images/remove.gif' name='remove[" + order_detail_id  + "]'/>";
	
	row.appendChild(cell_title);
	row.appendChild(cell_qty);
	row.appendChild(cell_free_qty);
	row.appendChild(cell_price);
	row.appendChild(cell_remove);
	return row;
}
						
function createNewOrderItemTable(offer_id,offer_name,class_id,class_name,child_id,child_name){
	// create a new empty table for this child or offer  and add it to the right place in the dom (within the class for this child or create a new class/child/offer and append it) (returns the table's id)
	
	var checkout_element = document.getElementById("checkout")
	$(checkout_element).removeClass("hidden");
	if(class_id){	 
		if($("fieldset#open_by_class ul.orders-sumary").length == 0){//append a ul.orders-sumary to the fieldset.open_by_class
			$("fieldset#open_by_class").append("<ul class=\"orders-sumary\">"); 
		} 
		
		var classDoesntExist = 1;
		var class_ul_id = 'class:' + class_id
		var class_ul = document.getElementById(class_ul_id);
		if (class_ul) {
			new_child = createOrderItem(child_id,child_name,0,0);
			class_ul.appendChild(new_child);
			
			// Add toggling
			//var handlers = new Array("#open_by_class li.current h4");
			//addEventHandlers(handlers, 0, "selected");
			
			classDoesntExist = 0;
		}else{
			var new_item = createClass(class_id, class_name);
			var new_child = createOrderItem(child_id,child_name,0,0);
			
			//append a li, h3, ul to ul.orders-sumary 
			var lists = document.getElementsByTagName("ul");
			for(i=0;i < lists.length;i++){
				if(lists[i].className.match("orders-sumary") && !lists[i].className.match("catalogues-summary")){
					lists[i].appendChild(new_item);
					document.getElementById(class_ul_id).appendChild(new_child);
					return false;
				}
			}	
		}
	} else{
		if($("ul.catalogues-summary").length == 0){
			$("fieldset#open_by_catalogue").prepend("<h3>Orders from</h3><ul class=\"orders-sumary catalogues-summary\">"); 
		} 
		new_item = createOrderItem(0,0,offer_id,offer_name);

		// append new li and h4 and table to ul.open_by_catalogue,
		var lists = document.getElementsByTagName("ul");
		for(i=0;i < lists.length;i++){
			if(lists[i].className.match("orders-sumary") && lists[i].className.match("catalogues-summary")){
				lists[i].appendChild(new_item);	
			}
		}	
	}
}

function createClass(class_id, class_name){
	var class_ul_id = 'class:' + class_id
	var new_item = document.createElement("li");
	var new_heading = document.createElement("h3");
	var new_list = document.createElement("ul");
	new_list.id = class_ul_id;
	
	var new_link = document.createElement("a");
	var link_text = "#" + class_ul_id;
	new_link.setAttribute("href", link_text);
	new_link.innerHTML = class_name;
	
	var class_total_p = document.createElement("p");
	$(class_total_p).addClass("summary-row");
	
	var class_total_p_label = document.createElement("label");
	class_total_p_label.innerHTML = "Total for " + class_name
	class_total_p.appendChild(class_total_p_label)
	var class_total_p_span = document.createElement("span");
	class_total_p_span.id = 'class_total_' + class_id;
	class_total_p.appendChild(class_total_p_span)

	new_heading.appendChild(new_link);
	new_item.appendChild(new_heading);
	new_item.appendChild(new_list);
	new_item.appendChild(class_total_p);
	return new_item;
}

function createOrderItem(child_id,child_name,offer_id,offer_name){ //creates a new order item

	var new_item = document.createElement("li");
	var new_heading = document.createElement("h4");
	var new_link = document.createElement("a");
	new_link.setAttribute("href", link_text);
	var tableID = 'summary_' 
	
	if(child_id){
		new_link.innerHTML = child_name;
 		tableID = tableID + 'child_id:' + child_id
	}else{
		new_link.innerHTML = offer_name;
 		tableID = tableID + 'offer_id:' + offer_id
	}	

	var link_text = "#" + tableID ;

	new_heading.appendChild(new_link);
	new_item.appendChild(new_heading);
	
	var new_table = document.createElement("table");
	
	new_table.setAttribute("id",tableID);
	new_item.appendChild(new_table);
	if (!child_id){
		var offer_total_p = document.createElement("p");
		$(offer_total_p).addClass("summary-row");
	
		var offer_total_p_label = document.createElement("label");
		offer_total_p_label.innerHTML = "Total"
		offer_total_p.appendChild(offer_total_p_label)
		var offer_total_p_span = document.createElement("span");
		offer_total_p_span.id = 'offer_total_' + offer_id;
		offer_total_p.appendChild(offer_total_p_span)
		new_item.appendChild(offer_total_p);	
	}

	return new_item;
}


/*********************

Expand collapse

**********************/

function prepareModule(subModules, handleNames, selectedClassName){
	closeSubModules(subModules);
	for(var i=0; i < handleNames.length; i++){
		theElement = handleNames[i];
		$(theElement).addClass("prepared");
	}	
	addEventHandlers(handleNames, 0, selectedClassName);
}
function closeSubModules(subModules){
	for(var i=0; i < subModules.length; i++){
		theElement = subModules[i];	
		$(theElement).hide();
	}	
}
function prepareNav() {
	var selectedClassName = "selected";
	addEventHandlers(handleNames, 0, selectedClassName);
}

function addEventHandlers(handleNames, toggleOthers, selectedClassName){
	for(var i=0; i < handleNames.length; i++){	
		theElement = handleNames[i];
		mouseOverAddClass(theElement);
		toggleMenuItems(theElement, toggleOthers, selectedClassName);
	}	
}
function mouseOverAddClass(theElement){	
	$(theElement).mouseover(function() {
		$(this).addClass(addedClass);
	});
	$(theElement).mouseout(function() {
		$(this).removeClass(addedClass);
	});
}
function toggleMenuItems(theElement, toggleOthers, selectedClassName){
	$(theElement + " a").click(function() {	
		theParent = this.parentNode;	
		toggleClass(theParent, selectedClassName);
		toggleSibling(theParent, 1);			// the elements in this container that aren't this click handler
		if(toggleOthers){
			toggleSibling(theParent.parentNode, 0); 	// the parent's siblings' children, i.e. the lists within other lists elements at this level
		}
		return false;
	});
	$(theElement).addClass("prepared");
}

function toggleSibling(theElement, toggleThis){
	var theSiblings = $(theElement).siblings().not(theElement);
	if(toggleThis){
		$(theSiblings).slideToggle("slow", function(){
			if($(theSiblings).is("table") && $(theSiblings).css("display") == "block"){$(theSiblings).css({ display:"table"}) };
		});
	}else{
		$(theSiblings).children("ul").hide("slow");
	}
}
function toggleClass(theItem, theClassName){
	if(theItem.className.indexOf(theClassName) != -1){
		$(theItem).removeClass(theClassName);
	}else{
		$(theItem).addClass(theClassName);
	}
}
function getLastClassName(fullClass){
	var temp = new Array();
	temp = fullClass.split(' ');
	theClass = temp[temp.length - 1];
	return theClass;
}


function prettyCurrency(amount, currency)
{
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = currency + minus + s;
	return s;
}

function increment_totals (offer_id, price, paid_qty, free_qty, child_id, class_id, currency)
{

	if (!class_id) {
		increment_one('offer_total_' + offer_id, paid_qty * price, currency);
	}else{
		increment_one('class_total_' + class_id, paid_qty * price, currency);
	}
	increment_one('order_paid_total', paid_qty * price, currency);
	increment_one('order_free_total', free_qty * price, currency);

}		

function increment_one(id, amount, currency)
{
	var element = document.getElementById(id)
	var cur_val = element.innerHTML
	if (cur_val) {
		var new_val = Number(cur_val.replace(/[^0-9|\.]/g, "")) + amount
	}else{		
		new_val = amount
	}		
	element.innerHTML = prettyCurrency(new_val, currency)
}		
