
var gTable;

function init() {
	
	// Turn on appropriate tab
	var tabFunction = eval("turnon_" + gActiveTab);
	tabFunction();

	$("#searchresultpanel").hide();	
	$("#expand").hide();
	
	document.all.hrpPartNo.focus();

	buildSupplierList();
	buildProductTypeList();
	
	// Check if first search
	if (gFirstSearch) {
		// If site is samsung then default manufacturer
		if (gSite=='samsung') {
			gSupplier = "13730";
		}
	}

	// Set HRP Part No
	if (gHRPPartNo!='' && gHRPPartNo!='0') {
		document.all.hrpPartNo.value=gHRPPartNo;
	}
	
	// Set Supplier
	if (gSupplier!='' && gSupplier!='0') {	
		setSelectionValue(document.all.suppCode, pad(gSupplier,"0",6));
	}

	// Set Supplier Part No
	if (gSuppPartNo!='') {
		document.all.suppPartNo.value=gSuppPartNo;
	}
		
	// Set keywords
	if (gKeywords!='') {
		document.all.kwds.value=gKeywords;
	}
	
	// Check if to rebuild hierarchy
	if (gHierarchySel!='') {
		for (var i=0; i<gHierArr.length; i++) {
			if (i==0) {
				setSelectionValue(eval("document.all.prdType1"), gHierArr[i]);
			}
			getProductTypes(gHierArr[i], (i+2));			
		}
	} else {
		dspTableRow('prdTypeRow2',false);
		dspTableRow('prdTypeRow3',false);
		dspTableRow('prdTypeRow4',false);		
		dspTableRow('prdTypeRow5',false);
	}

	$("#help_dialog").dialog({ 
		autoOpen: false,
		modal: true,
		width:  600,
		position: 'top'
	});
		
	// Perform mini basket initialisation
	initMiniBasket();
}

function buildSupplierList() {
	var suppCodeArray = gSuppCode.split("|");
	var suppDescArray = gSuppDesc.split("|");
	for (var x=0; x< suppCodeArray.length; x++) {
		addOption(document.all.suppCode, suppDescArray[x], suppCodeArray[x]);
	}
	return false;
}

function buildProductTypeList() {
	var prdTypeArray = gPrdType.split("|");
	var prdDescArray = gPrdDesc.split("|");	
	for (var x=0; x< prdTypeArray.length; x++) {
		addOption(document.all.prdType1, prdDescArray[x], prdTypeArray[x]);
	}
	return false;
}

function maskPage(text) {
	$("#mask").mask(text);
}

function unMaskPage() {
	$("#mask").unmask();
}

function enterAndEditKey(event,delimiters) {
  if (getKeyEvent(event) == 13)
    return searchFnc();
  return editKey(event,delimiters);
}

function validForm() {
	if (document.all.hrpPartNo.value=="" &&
		document.all.suppCode.value=="" &&
		document.all.suppPartNo.value=="" &&
		document.all.kwds.value=="" &&
		getSelectionValue(document.all.prdType1)=="") {
		alert(gMsg25);
		document.all.hrpPartNo.focus();
		return false;
	}
	
	// Validate sections - HRP Part No
	if (document.all.hrpPartNo.value!="" &&
		(document.all.suppCode.value!="" ||
		 document.all.suppPartNo.value!="" ||
		 document.all.kwds.value!="" ||
		 getSelectionValue(document.all.prdType1)!="")) {
		alert(gMsg38);	 
		return false;
	}
	
	// Validate sections - Supplier Code
	if (document.all.suppCode.value!="" &&
		(document.all.hrpPartNo.value!="" ||
		 document.all.kwds.value!="" ||
		 getSelectionValue(document.all.prdType1)!="")) {
		alert(gMsg38);	 
		return false;
	}
	
	// Validate sections - Supplier Part No
	if (document.all.suppPartNo.value!="" &&
		(document.all.hrpPartNo.value!="" ||
		 document.all.kwds.value!="" ||
		 getSelectionValue(document.all.prdType1)!="")) {
		alert(gMsg38);	 
		return false;
	}
	
	// Validate sections - Keywords
	if (document.all.kwds.value!="" &&
		(document.all.suppCode.value!="" ||
		 document.all.suppPartNo.value!="" ||
		 document.all.hrpPartNo.value!="" ||
		 getSelectionValue(document.all.prdType1)!="")) {
		alert(gMsg38);	 
		return false;
	}
	
	// Validate Product Hierarchy
	if (getSelectionValue(document.all.prdType1)!='') {
		if (document.all.prdType5.style.visibility=="visible") {
			return validProductType('prdType5');
		}
		if (document.all.prdType4.style.visibility=="visible") {
			return validProductType('prdType4');
		}
		if (document.all.prdType3.style.visibility=="visible") {
			return validProductType('prdType3');
		}
		if (document.all.prdType2.style.visibility=="visible") {
			return validProductType('prdType2');
		}
	}
	return true;
}

function validProductType(obj) {
	var prodObj = eval("document.all."+obj);
	var hierarchyUI = getSelectionValue(prodObj)
	if (hierarchyUI=='') {
		alert(gMsg27);
		prodObj.focus();
		return false;
	}	
	return true;
}

function getProductTypes(key, objNbr) {
		
	// Ensure subsequent dropdowns are invisible
	var strIdx = Number(objNbr);
	for (var i=strIdx; i<=5; i++) {
		dspTableRow('prdTypeRow'+i,false);
		var hideObj = eval("document.all.prdType"+i);
		hideObj.style.visibility="hidden";			
	}
	// Check if to get products or not	
	if (key!="") {
		var parmString = "key=" + key + "&nbr=" + objNbr;
		httpRequest(getProductTypesResponse, gPrdTypesURL, true, parmString);
	}
	return false;
}

function getProductTypesResponse(resString) {

		if (resString!="") {
			var resArray = resString.split("~");
	
			var objNbr  = resArray[0];
			var prdCode = resArray[1].split(gDelimiter);
			var prdDesc = resArray[2].split(gDelimiter);
		
			// Build new dropdown list if applicable
			if (prdCode!="") {
				dspTableRow('prdTypeRow'+objNbr,true);
				var droplist = eval("document.all.prdType"+objNbr);
				droplist.options.length = 0;
				addOption(droplist,"","");
				for (var i=0; i<prdCode.length; i++) {
					addOption(droplist,prdDesc[i],prdCode[i]);
				}
				droplist.style.visibility="visible";
				
				// Check if to set selection value
				if (gHierArr[objNbr-1]!='') {
					setSelectionValue(droplist, gHierArr[objNbr-1]);
				}
			}
		}
	return false;
}

function getHierarchyUI() {
	var hierarchyUI = getSelectionValue(document.all.prdType5);
	if (hierarchyUI!='') {
		return hierarchyUI;
	}
	hierarchyUI = getSelectionValue(document.all.prdType4);
	if (hierarchyUI!='') {
		return hierarchyUI;
	}
	hierarchyUI = getSelectionValue(document.all.prdType3);
	if (hierarchyUI!='') {
		return hierarchyUI;
	}
	hierarchyUI = getSelectionValue(document.all.prdType2);
	if (hierarchyUI!='') {
		return hierarchyUI;
	}
	hierarchyUI = getSelectionValue(document.all.prdType1);
	if (hierarchyUI!='') {
		return hierarchyUI;
	}
	return 0;
}

function getHierarchySel() {
	var selection = "";
	var selectionText = "";
	hierarchyUI = getSelectionValue(document.all.prdType1);
	if (hierarchyUI!='') {
		selection += hierarchyUI;
		selectionText += getSelectionTextValue(document.all.prdType1);
	}
	hierarchyUI = getSelectionValue(document.all.prdType2);
	if (hierarchyUI!='') {
		selection += "|" + hierarchyUI;
		selectionText += ", " + getSelectionTextValue(document.all.prdType2);
	}
	hierarchyUI = getSelectionValue(document.all.prdType3);
	if (hierarchyUI!='') {
		selection += "|" + hierarchyUI;
		selectionText += ", " + getSelectionTextValue(document.all.prdType3);
	}		
	hierarchyUI = getSelectionValue(document.all.prdType4);
	if (hierarchyUI!='') {
		selection += "|" + hierarchyUI;
		selectionText += ", " + getSelectionTextValue(document.all.prdType4);
	}
	var hierarchyUI = getSelectionValue(document.all.prdType5);
	if (hierarchyUI!='') {
		selection += "|" + hierarchyUI;
		selectionText += ", " + getSelectionTextValue(document.all.prdType5);
	}
	return [selection, selectionText];
}

function buildKeywordString() {
	// Build temp array of keywords
	var keywords = document.all.kwds.value.toUpperCase();
	var tmpArray = keywords.split(" ");
	
	// Loop through array and build new string
	var keywordString = "";
	for (x=0; x<tmpArray.length; x++) {
		if (tmpArray[x]!='') {
			keywordString += trim(tmpArray[x]) + gDelimiter;
		}	
	}
	return keywordString;
}

function formatHierarchyText(text) {
	if (text.length>50) {
		var newText = "..." + text.substring(text.length-50, text.length);
		return newText;
	}
	return text;
}

function searchFnc() {
	if (validForm()) {
		maskPage('Searching...');
		$("#searchresultpanel").hide();		
		setTimeout(searchFncQuery, 100);
	}
	return false;
}

function searchFncQuery() {
	// Make request
	var parmString = "hrpPartNo=" + trim(document.all.hrpPartNo.value);
	parmString += "&keywordSearch=" +  document.all.kwds.value;
	parmString += "&keywords=" + buildKeywordString();
	parmString += "&suppCode=" + getSelectionValue(document.all.suppCode);
	parmString += "&suppPartNo=" + trim(document.all.suppPartNo.value.toUpperCase().replace(/\-/g,""));
	parmString += "&hierarchyUI=" + getHierarchyUI();
	var obj = getHierarchySel();
	parmString += "&hierarchySel=" + obj[0];
	parmString += "&hierarchySelText=" + formatHierarchyText(obj[1]);
	parmString += "&x=" + new Date().getTime();
	httpRequest(getSearchProductsResponse, gSearchProductsURL, true, parmString);
}

var gJsonObj;

function getSearchProductsResponse(resString) {
	
		if (resString=="") {
			// Show error
		} else {
			var jsonFile = "gJsonObj = " + resString;
			eval(jsonFile);
			
			// Move result rows to an array if it not already
			var gRowsArray;
			if (gJsonObj.products=="") {
				gRowsArray = new Array();
			} else {
				if (gJsonObj.products.rowdata.length>1) {
					gRowsArray = new Array(gJsonObj.products.rowdata.length);
					gRowsArray = gJsonObj.products.rowdata;
				} else {
					gRowsArray = new Array(1);
					gRowsArray[0] = gJsonObj.products.rowdata;
				}
			}
					
			$('#dynamic').html( '<table cellpadding="0" cellspacing="0" border="0" class="display" id="datatableid"></table>' );
			
			// Build product rows
			var rowsArray = new Array();
			if (gJsonObj.products!="") {
				rowsArray = new Array(gRowsArray.length);
			}
			
			for (x = 0; x < gRowsArray.length; x++) {
				
				var addIcon = "";
				if (gIsLO) {
					addIcon = "&nbsp;&nbsp;<span title=\"Add to order\" onclick=\"return addProduct(" + x +")\"><img id=\"prodadd" + x + "\" style=\"cursor:pointer;\" align=\"top\" src=\"script/jquery/images/icons/additem.png\" height=\"18\">";
				}
				
				// Build row array
				var rowData = [
						gRowsArray[x].sequence,
						"<a href=\"#\" class=\"underline\" onclick=\"return showInfo(" + x +");\">" + gRowsArray[x].hrpPartNo + "</a>",
						gRowsArray[x].suppPartNo,
						gRowsArray[x].description,
						CurrencyFormatted(gRowsArray[x].unitPrice.value,2),
						CurrencyFormatted(gRowsArray[x].salePrice.value,2) + addIcon
					];
				rowsArray[x] = rowData;
			}
			
			// Turn off sorting icons
			$.fn.dataTableExt.oStdClasses.sSortAsc = "";
			$.fn.dataTableExt.oStdClasses.sSortDesc = "";
			$.fn.dataTableExt.oStdClasses.sSortable = "";
			 
			gTable = $('#datatableid').dataTable( {
				"aoColumns": [
					{ "sTitle": "Sequence", "bSearchable": false, "bVisible": false },
					{ "sTitle": "HRP Code No.", "sClass": "leftAdjust", "sWidth" : "15%", "sType": "html" },
					{ "sTitle": "Manf. Part No.", "sClass": "leftAdjust", "sWidth" : "15%" },
					{ "sTitle": "Description", "sClass": "leftAdjust", "sWidth" : "40%" },
					{ "sTitle": "List Price (GBP)", "sClass": "rightAdjust", "sWidth" : "15%"},
					{ "sTitle": "Your Price (GBP)", "sClass": "rightAdjust", "sWidth" : "15%" }
				],
				"aaSorting": [[ 0, "asc" ]],
				"aaData": rowsArray,
				"bPaginate": true,
				"sPaginationType": "full_numbers",
				"bLengthChange": false,
				"iDisplayLength": 20,
				"bFilter": false,
				"bSort": true,
				"bInfo": true,
				"bAutoWidth": false,
				"bProcessing": false
				} );
						
			$("#searchresultpanel").show("blind","slow");
			unMaskPage();
		}
	
}

function expand() {
	$("#searchpanel").show();
	$("#expand").hide();
	$("#collapse").show();	
}

function collapse() {
	$("#searchpanel").hide();
	$("#expand").show();
	$("#collapse").hide();
}

function showInfo(idx) {
	$("#infodialog").load("ProductInformationModal.jsp", 
					{"idx" : idx,
					 "x"  : new Date().getTime()},
					function(){
						$('#infodialog').dialog('open');
						unMaskPage();
					}).dialog({ 
				       	 title: 'Product Information',
				       	 autoOpen: false,
				       	 modal: true, 
				       	 draggable: true, 
				       	 resizable: true,
				       	 width: 600
					}
	);
	return false;
}

var gIdxAdd;

function addProduct(idx) {
	var parmString = "idx=" + idx;
	gIdxAdd = idx;
	httpRequest(getAddProductResponse, gAddProductURL, true, parmString);
	return false;
}

function getAddProductResponse(resString) {
	
		if (resString=="") {
			$("#prodadd"+gIdxAdd).effect("transfer",			
				{ to: "#yourorder", 
				  className: 'ui-effects-transfer' }
				,750, getOrderInformation);
			
			// Set on tick image
//			var tickImage = eval("document.all.prodtick" + gIdxAdd);
//			tickImage.style.visibility = "visible";
		} else {
			alert(gMsg34);
		}
		gIdxAdd = 0;
	
}


function resetForm() {
	document.all.hrpPartNo.value = "";
	document.all.suppPartNo.value = "";
	document.all.kwds.value = "";
	getProductTypes("",2);
	document.all.suppCode.selectedIndex = 0;
	document.all.prdType1.selectedIndex = 0;
	document.all.prdType2.selectedIndex = 0;
	document.all.prdType3.selectedIndex = 0;
	document.all.prdType4.selectedIndex = 0;
	document.all.prdType5.selectedIndex = 0;
	return false;
}

function showHelp() {
	var helpHTML = "<img style=\"cursor:pointer;\" src=\"script/jquery/images/search_help.jpg\">";
	$('#help_dialog').dialog('open').html(helpHTML);
	return false;
}

