/* 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').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;
	 }
	});
	addPlusMinus("form:not(#order_form) td input[@name=paid_qty][@type=text]");
	addPlusMinus("form:not(#order_form) td input[@name=free_qty][@type=text]");
	increment(".increment");
	decrement(".decrement");
	
	$(".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 addPlusMinus(input_text){
	$(input_text).each( function(){
		$(this).after("<img src='images/buttons/button_minus.gif' alt='-' class=\"decrement\" /><img src='images/buttons/button_plus.gif' alt='+' class=\"increment\" />");
	});
}
	
function increment(image_button) {
	$(image_button).bind("click", function() {
		qty_field = $(this).parent("td").find("input[@type=text]");
		var numValue = $(qty_field).val(); 
		numValue++;
		$(qty_field).val(numValue);
	});
}			
function decrement(image_button) {
	$(image_button).bind("click", function() {
		qty_field = $(this).parent("td").find("input[@type=text]");
		var numValue = $(qty_field).val(); 
		if (numValue > 0 ) {
		numValue--;
		}
		$(qty_field).val(numValue);
	});
}		
	 


/*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").val("");
	});
	$("input#sbc_seq").change(function(){
	    $.getJSON("fetchItem.js",{sbc_seq: $(this).val(), offer_id: $("select#offer_id").val() }, function(j){
		    if(j.return_code == "OK") {
		        output_title = '<p>' + j.title + '</p>';
		    }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>";
				}
			}
		    $("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: "addNewOfferItemOffer.js",
		data: {	sbc_seq: $(this.sbc_seq).val(), 
				offer_id: $(this.offer_id).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 == "OK"){	
				
				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);
				var table_for_offer_child = findOrderItemTable(added_item.offer_id,added_item.child_id); // find place in the DOM for  order/child
				
				if(!table_for_offer_child){ // or if there aren't existing items for this offer/child 	
					table_for_offer_child = createNewOrderItemTable(added_item.offer_id,added_item.offer_name,added_item.class_name,added_item.child_id,added_item.child_name,added_item.child_total,added_item.offer_total,added_item.class_paid_total); // create a new table and inject it into the DOM at the right place 
				}
				$("#" + table_for_offer_child).append(new_row);
				increment("#" + table_for_offer_child + " .increment");
				decrement("#" + table_for_offer_child + " .decrement");
				$("#" + 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");
				
				if(added_item.child_name){
					setClassTotal(table_for_offer_child, added_item.child_total, added_item.class_paid_total);// in the appropriate Class span
				} else{
					$("#" + table_for_offer_child).parents("li.current").find("span.offer_total").text(added_item.offer_total);
				}
				
				$("#form-message").text("Added one item to " + ( added_item.class_name ? added_item.class_name : added_item.offer_name)).show("slow").fadeOut(2000);
				
				$("span#order_paid_total").html(added_item.order_paid_total);	// set grand total
			
			}
		},
		error: function(msg){
			if(msg.status == 0){
				alert("uninitialised ajax: " + msg.responseText);
			}
		}
	});
	
	return false;
	
  });
}

function removeItem(){
  $("form#open_order_summary td.remove 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,order_detail_id,child_id){
	// create a <tr> with the relevant information in it. (returns a tr element)
	
	
	
	var row = document.createElement("tr");
	var cell_title = document.createElement("td");
	cell_title.className = "title";
	var cell_qty = document.createElement("td");
	var cell_free_qty = document.createElement("td");
	var cell_price = document.createElement("td");
	var cell_remove = document.createElement("td");
	
	cell_title.innerHTML = item_title;
	
	cell_qty.innerHTML = "<input type='text' class='text' name='paid_qty' value='" + paid_qty + "' size='3' /><input type='hidden' name='order_detail_id' value='" + order_detail_id + "' />";
	if(child_id){
		cell_qty.innerHTML += "<input type='hidden' name='child_id' value='" + child_id + "' />"
	}
	
	cell_qty.innerHTML += "<img src='images/buttons/button_minus.gif' alt='-' class=\"decrement\" /><img src='images/buttons/button_plus.gif' alt='+' class=\"increment\" />";
	
	cell_free_qty.innerHTML =	"<input type='text' class='text' name='free_qty' value='" + free_qty + "' size='3' />";
	cell_free_qty.innerHTML += "<img src='images/buttons/button_minus.gif' alt='-' class=\"decrement\" /><img src='images/buttons/button_plus.gif' alt='+' class=\"increment\" />";
	cell_price.innerHTML = "&pound;<span class='price'>" + price + "</span>";
	cell_price.className = 'currency';
	cell_remove.innerHTML = "<input type='image' src='images/buttons/remove.gif' />";
	
	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_name,child,child_name,child_total,offer_total,class_paid_total){
	// 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 tableID = 0;
	if(class_name){	 
			
		if($("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_number = 'Class0';
		$("ul.orders-sumary h3 a").each( function(){
			class_number = $(this).attr("href");
			if($(this).html() == class_name){	// there is a class for this new item
				new_child = createOrderItem(child,child_name,0,0,child_total,0);
				theParent = this.parentNode;
				theParent = theParent.parentNode;
				var kids = theParent.childNodes;
				for(i=0;i < kids.length;i++){
					if(kids[i].nodeName.toLowerCase() == "ul"){
						kids[i].appendChild(new_child);
					}
				}
				for(i=0;i < new_child.childNodes.length;i++){
					if(new_child.childNodes[i].nodeName.toLowerCase() == "table"){
						tableID = new_child.childNodes[i].id;
					}
				}
				
				// Add toggling
				//var handlers = new Array("#open_by_class li.current h4");
				//addEventHandlers(handlers, 0, "selected");
				
				classDoesntExist = 0;
				return false;
			}
		});
		
		if(classDoesntExist){/*there is no existing class with this class_name*/
			class_number = 'Class' + ((class_number.substring(6)*1)+1);
			var new_item = createClass(class_number, class_paid_total, class_name);
			var new_child = createOrderItem(child,child_name,0,0,child_total,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_number).appendChild(new_child);
					
				}
			}	
			for(j=0;j < new_child.childNodes.length;j++){
				if(new_child.childNodes[j].nodeName.toLowerCase() == "table"){
					tableID = new_child.childNodes[j].id;
				}
			}	
		}
		
	} 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,0,offer_total);
		for(k=0;k < new_item.childNodes.length;k++){
			if(new_item.childNodes[k].nodeName.toLowerCase() == "table"){
				tableID = new_item.childNodes[k].id;
			}
		}
		// 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);	
			}
		}	
	}
	return tableID;
}

function createClass(class_number, class_paid_total, class_name){
	var new_item = document.createElement("li");
	var new_heading = document.createElement("h3");
	var new_list = document.createElement("ul");
	new_list.id = class_number;
	
	var new_link = document.createElement("a");
	var link_text = "#" + class_number;
	new_link.setAttribute("href", link_text);
	new_link.innerHTML = class_name;
	
	var new_span = document.createElement("span");
	new_span.innerHTML = "&pound;";
	var new_price_span = document.createElement("span");

	new_price_span.className = "class_paid_total";
	new_price_span.innerHTML = class_paid_total;

	new_span.appendChild(new_price_span);	
	
	new_heading.appendChild(new_link);
	new_heading.appendChild(new_span);	
	new_item.appendChild(new_heading);
	new_item.appendChild(new_list);
	return new_item;
}

function createOrderItem(child,child_name,offer_id,offer_name,child_total,offer_total){ //creates a new order item

	var new_item = document.createElement("li");
	var new_heading = document.createElement("h4");
	
	var tableID = incrementItemID();
	var new_link = document.createElement("a");
	var link_text = "#" + tableID ;
	new_link.setAttribute("href", link_text);
	
	if(child){
		new_link.innerHTML = child_name;
	}else{
		new_link.innerHTML = offer_name;
	}
	
	var new_span = document.createElement("span");
	new_span.innerHTML = "&pound;";
	var new_price_span = document.createElement("span");

	if(child){
		new_price_span.className = "child_total";
		new_price_span.innerHTML = child_total;
	}else{
		new_price_span.className = "offer_total";
		new_price_span.innerHTML = offer_total;
	}

	new_span.appendChild(new_price_span);	
	
	new_heading.appendChild(new_link);
	new_heading.appendChild(new_span);	
	new_item.appendChild(new_heading);
	
	var new_table = document.createElement("table");
	
	new_table.setAttribute("id",tableID);
	new_item.appendChild(new_table);
	return new_item;
}

function incrementItemID(){
	// add a new ID number for this child/order
	var tableID = "Summary0";
	$("form#open_order_summary table").each( function(){ tableID = this.id; });
	var suffix = tableID.substring(7);
	tableID = "Summary" + (parseInt(suffix, 10) + 1);
	return tableID;
}

function findOrderItemTable(offer_id,child){
	// returns the id of the table for child, or offer if there's no child 
	var theID = 0;
	if(child){
		$("ul.orders-sumary li li input[@name=child_id]").each( function(){		
			if($(this).val() == child){
				theID = $(this).parents("table").attr("id");
				return false;
			}
		});	
	}
	else{
		$("ul.catalogues-summary li").each( function(){	
			if($(this).attr("id").substring(9) == offer_id){ // id less "offer_id:"
				theID = $(this).find("table").attr("id");
				return false;
			} 
		})
	}
	
	return theID;
}



function setClassTotal(table_row, child_total, class_paid_total){
	// set the value in the total <span> for this child
	$("#" + table_row).parents("li.current").find("span.child_total").text(child_total);
	$("#" + table_row).parents("ul").prev("h3").find("span.class_paid_total").html(class_paid_total);
}

/*********************

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;
}
