//this requires jquery and the var to be called $j to avoid conflict with prototype.js

var _CATEGORY_LNAME = "categoryCats";
var _BRAND_LNAME = "brandId";
var _MARKET_LNAME = "marketId";
//'/img/working.gif'
var _workingImageLocation=null;//'/images/working.gif';
function clearDetailSearch(){
	document.getElementById('detailSearchTerm').value="";
	document.getElementById('detailSearchTerm_adv').value="";
	document.getElementById(_BRAND_LNAME).selectedIndex=0;
	document.getElementById(_CATEGORY_LNAME).selectedIndex=0;
	document.getElementById(_MARKET_LNAME).selectedIndex=0;
	
//ideally these should be hidden
	eraseList(document.getElementById('marketCats'));
	eraseList(document.getElementById('marketSubCats'));
	eraseList(document.getElementById('brandCats'));
	eraseList(document.getElementById('brandSubCats'));

/*	document.getElementById('marketCats').selectedIndex=0;
	document.getElementById('marketSubCats').selectedIndex=0;
	document.getElementById('brandCats').selectedIndex=0;
	document.getElementById('brandSubCats').selectedIndex=0;*/
}
function getSearchType(searchKey) {
    switch (searchKey) {
        case "brandId":
        case "brandCleanName":
            return SEARCHTYPE = 0;
        case "marketId":
        case "marketCleanName":
            return SEARCHTYPE = 1;
        case "categoryId":
        case "categoryCleanName":
            return SEARCHTYPE = 2;
        default:
        	return 'UNKNOWN: ' + searchKey;
    }
}
function getSelectedRadioButton(){
	var io=null;
	io=document.getElementById('radCategory');
	if(io.checked)return io;
	io=document.getElementById('radBrand');
	if(io.checked)return io;
	io=document.getElementById('radMarket');
	if(io.checked)return io;
	return null;
}
function setChildListToWait(clistname){
	var chillist = getList(clistname);
	
	eraseList(chillist);
	addToChoiceList(chillist,"Select Category First",'');
}

function getCategoryBy(searchKey,searchKeyVal,targetSelect,targetChildSelect,workingSpan){
	//reset until a category is picked
	setCategoryValue('');
	setSubCategoryValue('');
	
	var list = getList(targetSelect);
	
	eraseList(list);
	addToChoiceList(list,"Loading...",'');
	
	setChildListToWait(targetChildSelect);
	
	startWorking(workingSpan);
	
	var searchType = getSearchType(searchKey);

	// do the AJAX calls using the DWR libraries
    // first set up values to pass as attributes to the call
    var map = {};
    map.productAttribute = searchType;
   
    map[searchKey] = searchKeyVal;

//alert(searchType + " " + searchKey + " " +searchKeyVal);
    // now do the call itself, returning the data to the
    // displaySubCategories() function to populate the sub-categories
    // column in the browser
    //JProductByAttribute.getDwrCategoryListMap(map, displayCategories);
	//if resp is null check that the webservices/datasources are up on the appconfig
    JProductByAttribute.getDwrCategoryListMap(map, {
	  callback:function(resp) { if(!resp)alert('The system may be down please try again later.');displayCategories(resp,targetSelect,workingSpan); }
	});
}
function setCategoryValue(val){
	//if(!val)return;
	document.getElementById('categoryId').value=val;
}
function setSubCategoryValue(val){
	//if(!val)return;
	document.getElementById('subCategoryId').value=val;
}

function getSubCategoryBy(searchKey,searchKeyVal,oldSearchKey,oldKeyVal,parentSelect,targetSelect,workingSpan){
	setCategoryValue(searchKeyVal);
	setSubCategoryValue('');
	
	if( !searchKeyVal || searchKeyVal == '' || searchKeyVal.length == 0 ){
		setChildListToWait(targetSelect);
		return;
	}
	
	startWorking(workingSpan);
	
	//alert(searchKey + " " + searchKeyVal + " " + oldSearchKey + " " + oldKeyVal);
	
	var list = getList(targetSelect);
	
	eraseList(list);
	addToChoiceList(list,"Loading...",'');
	
	var searchType = -1;
	if(oldSearchKey){
		searchType = getSearchType(oldSearchKey);
	}else{
		searchType = getSearchType(searchKey);
	}
	
	// do the AJAX calls using the DWR libraries
    // first set up values to pass as attributes to the call
    var map = {};
    map.productAttribute = searchType;
	map[oldSearchKey] = oldKeyVal;
    map[searchKey] = searchKeyVal;

    // now do the call itself, returning the data to the
    // displaySubCategories() function to populate the sub-categories
    // column in the browser

    JProductByAttribute.getDwrSubCategoryListMap(map, {
	  callback:function(resp) { if(!resp)alert('The system may be down please try again later.');displaySubCategories(resp,parentSelect,targetSelect,workingSpan); }
	});
}
function getList(lid){
	var list = document.getElementById(lid);
	
	if( !list ){
		alert("could not find list " + lid);
	}
	return list;
}
function displaySubCategories(response,t,tt,w) {
    // parse through the data and make it into an array to loop through
    var results = createArry(response);
    
    var list = getList(tt);
	var parentList = getList(t);
	
    eraseList(list);
    
    addToChoiceList(list,'All',parentList.options[parentList.selectedIndex].value);
    for(var x=0;x<results.length;x++){
    	addToChoiceList(list,results[x].categoryName,results[x].categoryId);
    }
    
    doneWorking(w);
}
function doneWorking(w){
	if(!_workingImageLocation)return;
	$j("#"+w).html("");
}
function startWorking(w){
	if(!_workingImageLocation)return;
	$j("#"+w).html("<img alt='...' src='"+_workingImageLocation+"'/>");//&nbsp;&nbsp;&nbsp;Searching...
	//alert(w + " " + $j("#"+w).html());
}
function displayCategories(response,t,w) {
    // parse through the data and make it into an array to loop through
    var results = createArry(response);
    
    var list = getList(t);
	
    eraseList(list);
    
    addToChoiceList(list,'All','');
    for(var x=0;x<results.length;x++){
    	addToChoiceList(list,results[x].categoryName,results[x].categoryId);
    }
    
    doneWorking(w);
}
function addToChoiceList(obj,t,v){
	t=t.replace('&amp;','&');
	//t=t.replace('&reg;','®');
	//
	t=unescape(t);
	//t=t.replace('&amp;','&');
	//t=t.replace('&trade;','&');
	AddMe = new Option(t,v);
	obj.options[obj.options.length] = AddMe;
	//obj.selectedIndex = 0;
}
function eraseList(obj){
	//removes the current list
	while(obj.options.length!=0){
		obj.options[0]=null;
	}
}
function createArry(resp) {
    var ar = Array();
    
    var n = 0;

    // do we even have data?
    if (resp.length) {

        // loop through all items, assigning them as items in the array
        for (var prop in resp) {
			//because of prototype.js, it extends object and gives an object all sorts of functions
			//, we need to ignore those when we loop
			//values from dwr are numbered 0,1,2,3,...
		     if(isNaN(prop)==false){
			//alert(prop + " " + resp[prop]);
	              ar[n] = resp[prop];
				n++;
		     }
            
        }

    } else if (resp && (resp != '')) {
        ar[0] = resp;
    }

    return ar;
}
function _preloadImg(image) {
	var img = new Image();
	img.src = image;
}
function initialize(){
	if(_workingImageLocation){
		_preloadImg(_workingImageLocation);
	}
	
	$j(document).ready(function() {
		/*
		//does not have to be called because we populate server side now
		if( $j("#"+_BRAND_LNAME).attr('value') > 0 
				&& ( !$j("#brandCats").attr('value') || $j("#brandCats").attr('value') <= 0 ) ){
			getCategoryBy("brandId",$j("#"+_BRAND_LNAME).attr('value'),'brandCats','brandSubCats','brandCatWorkingTag');
		}
		if( $j("#"+_MARKET_LNAME).attr('value') > 0  
			&& ( !$j("#marketCats").attr('value') || $j("#marketCats").attr('value') <= 0 )){
			getCategoryBy("marketId",$j("#"+_MARKET_LNAME).attr('value'),'marketCats','marketSubCats','marketCatWorkingTag');
		}
		if( $j("#"+_CATEGORY_LNAME).attr('value') > 0  
			&& ( !$j("#categorySubCats").attr('value') || $j("#categorySubCats").attr('value') <= 0 )){
			alert("CC");
			getSubCategoryBy('categoryId',$j("#_CATEGORY_LNAME").attr('value'),null,null,_CATEGORY_LNAME,'categorySubCats','categoryCatWorkingTag');
		}*/
		
		//BRANDS
		$j("#"+_BRAND_LNAME).change(function() {
			//onchange="getCategoryBy(_BRAND_LNAME,this.value,'brandCats','brandSubCats','brandCatWorkingTag')">
			getCategoryBy("brandId",this.value,'brandCats','brandSubCats','brandCatWorkingTag');
		});
		
		$j("#brandCats").change(function() {
			//onchange="getSubCategoryBy('categoryId',this.value,'brandCats','brandSubCats','brandCatWorkingTag')"
			getSubCategoryBy('categoryId',this.value,"brandId",document.getElementById(_BRAND_LNAME).value,'brandCats','brandSubCats','brandCatWorkingTag');
		});
		$j("#brandSubCats").change(function() {
			//onchange="setCategoryValue(this.value)"
			setSubCategoryValue(this.value);
		});
		
		//MARKETS
		$j("#"+_MARKET_LNAME).change(function() {
			//onchange="getCategoryBy(_MARKET_LNAME,this.value,'marketCats','marketSubCats','marketCatWorkingTag')"
			getCategoryBy("marketId",this.value,'marketCats','marketSubCats','marketCatWorkingTag');
		});
		$j("#marketCats").change(function() {
			//onchange="getSubCategoryBy('categoryId',this.value,'marketCats','marketSubCats','marketCatWorkingTag')"
			getSubCategoryBy('categoryId',this.value,"marketId",document.getElementById(_MARKET_LNAME).value,'marketCats','marketSubCats','marketCatWorkingTag');
		});
		$j("#marketSubCats").change(function() {
			//onchange="setCategoryValue(this.value)"
			setSubCategoryValue(this.value);
		});
		
		//CATEGORIES
		$j("#categoryCats").change(function() {
			//onchange="getSubCategoryBy('categoryId',this.value,_CATEGORY_LNAME,'categorySubCats','categoryCatWorkingTag')"
			getSubCategoryBy('categoryId',this.value,null,null,_CATEGORY_LNAME,'categorySubCats','categoryCatWorkingTag');
		});
		$j("#categorySubCats").change(function() {
			//onchange="setCategoryValue(this.value)"
			setSubCategoryValue(this.value);
		});
	});
}
initialize();
