// Initial set up of tabs
var kw_selected_tab = 'tab0';
var visible_page = -1;
var KWResults;




var kwresults_pager = function(){

	var i;
	var p;
	var r;
	var oe;

	

	this.type                     = "page";
	this.page_links_base_id       = "kw_page_links";
	this.result_base_id           = "kwresult";
	this.drop_down_base_id        = "kwresults_pp_form";
	this.drop_down_select_base_id = "kwresults_pp_select";

	this.results = [];
	this.results_per_page = 0;

	this.pages = [];
	this.results_on = [];
	this.page_current = 0;
	this.page_previous = 0;
	this.pages_max = 50;
	
	this.prev_links = [];
	this.next_links = [];

	this.page_links = [{id: "",
						element: null,
						links: []
					   }];

	this.drop_downs = [{id: "",
						element: null,
						select: null}];

	this.drop_down_pp = [5,10,15];

	this.drop_down_current = 0;
	this.drop_down_previous = 0;
	this.drop_down_change_enabled = true;

	

	
	this.init_results = function(){
		var r;
		var s;
		var i;

		
		for(i = 0; (r = dojo.byId(this.result_base_id + i)) && typeof(r) !== 'undefined'; i++){
			oe = i % 2;
			r.style.display = "none";
			this.results[i] = { element: r,
								oe:  oe
								};
		}

		
		this.drop_downs = [];
		for(i = 0; (r = dojo.byId(this.drop_down_base_id + i)) && typeof(r) !== 'undefined'; i++){
			s = dojo.byId(this.drop_down_select_base_id + i);
			this.drop_downs[i] = {	id: this.drop_down_base_id + i,
									element: r,
									select: s
								};
			this.drop_downs[i].select.onchange = function(){KWResults.on_dd_change(this.selectedIndex, this.options[this.selectedIndex].value);};	
		}

		if((this.drop_down_pp.length === 0) || (this.drop_downs.length === 0)){
			this.results_per_page = Math.floor(Math.max(KW_PAGE_CONFIG.slot_height * KW_PAGE_CONFIG.min_slots, windowHeight() - KW_PAGE_CONFIG.unusable_height - KW_PAGE_CONFIG.table_unusable_height) / KW_PAGE_CONFIG.slot_height);
		} else {
			this.results_per_page = this.drop_down_pp[0];
		}			

		if(this.results_per_page > this.results.length || this.results_per_page === -1){
			this.results_per_page = this.results.length;
		}

		this.set_pages();

		if(this.drop_downs.length > 0){
			this.init_dropdowns();
		} 

		this.drop_down_current = 0;
		this.drop_donw_previous = 0;

		
		this.page_links = [];
		for(i = 0; (r = dojo.byId(this.page_links_base_id + i)) && typeof(r) !== 'undefined'; i++){
			this.page_links[i] = {	id: this.page_links_base_id + i,
									element: r,
									links: []
								};	
		}

	}

	
	this.init_dropdowns =  function(){

		var i;
		var j;
		var o;
		this.drop_down_change_enabled = false;
		if(this.drop_down_pp.length === 0 && this.drop_downs.length !== 0){
			for(i = 0, j = this.results_per_page; i < this.pages.length && i < 4; i++, j += this.results_per_page){
				this.drop_down_pp[i] = j;
			}
		}

		for(i = 0; i < this.drop_downs.length; i++){
			if(this.pages.length <= 1){
				this.drop_downs[i].element.style.display = 'none';
			} else {
				this.drop_downs[i].select.options.length = 0;
				for(j = 0; j < this.drop_down_pp.length; j++){
					if(this.drop_down_pp[j] >= this.results.length){
						break;
					}
					o = document.createElement('option');
					o.innerHTML = this.drop_down_pp[j] + " per page";
					o.value = this.drop_down_pp[j];
					if(j === 0){
						o.selected = true;
					}
					this.drop_downs[i].select.appendChild(o);
				}
				o = document.createElement('option');
				o.innerHTML = "all results";
				o.value = -1;
				this.drop_downs[i].select.appendChild(o);
			}
		}

		this.drop_down_change_enabled = true;
	}	


	
	this.on_dd_change = function(index, pp){
		var i;

		if(this.drop_down_change_enabled === false){
			return;
		}

		this.drop_down_previous = this.drop_down_current;
		this.drop_down_current = index;

		if(this.drop_downs.length > 1){
			this.set_dropdowns();
		}

		if(pp >= this.results.length){
			this.results_per_page = this.results.length;
		} else {
			var ipp = parseInt(pp);
			if(ipp == -1){
				this.results_per_page = this.results.length;
			} else {
				this.results_per_page = ipp;
			}
		}

		for(i = 0; i < this.page_links.length; i++){
			this.page_links[i].links = [];
		}

		this.set_pages();
		this.show_page(0);
	}


	
	this.set_dropdowns = function(sync){
		var i;
		var ddbox;

		this.drop_down_change_enabled = false;

		for(i = 0; i < this.drop_downs.length; i++){
			ddbox = this.drop_downs[i].select;
			ddbox.options[this.drop_down_previous].selected = false;
			ddbox.options[this.drop_down_current].selected = true;
		}

		this.drop_down_change_enabled = true;
	}


	
	this.set_pages = function(){
		var i;
		var j;
		this.pages = [];
		for(i = 0, j = 0; (j < this.results.length) && (i < this.pages_max); i++, j += this.results_per_page){
			this.pages[i] = j;
		}
	}

	
	this.set_links = function(){

		var i;
		var j;
		var link;
		var txt;
		var sep;
		var e;
		var link_click_handler = function(p){
					return function(){
						KWResults.show_page(p);
					};
				}
		for(i = 0; i < this.page_links.length; i++){
			if(this.pages.length <= 1){
				if(this.page_links[i].element.innerHTML){
					this.page_links[i].element.innerHTML = "";
				}
			} else {
				if(this.page_links[i].links.length === 0){
					this.page_links[i].element.innerHTML = "";
					for(j = 0; j < this.pages.length; j++){
						txt  = document.createTextNode((j+1) + "");

						link = document.createElement('a');
						
						link.id = "kw_page_link" + j;
						if(j === this.page_current){
							link.className = "kw_page_link_current";
						} else {
							link.className = "kw_page_link_active";
						}
						link.onclick = link_click_handler(j);
						link.appendChild(txt);
						this.page_links[i].element.appendChild(link);
						if(j !== (this.pages.length - 1)){
							sep = document.createTextNode(" | ");
							this.page_links[i].element.appendChild(sep);
						}
						this.page_links[i].links[j] = link;
					}
				} else {
					this.page_links[i].links[this.page_previous].className = "kw_page_link_active";
					this.page_links[i].links[this.page_current].className = "kw_page_link_current";
				}
			}
		}
	}	


	
	this.show_page = function(page){
		var i;
		var last;

		last = this.pages[this.page_current] + this.results_per_page;

		
		for(i = 0; i < this.results_on.length; i++){
			this.results[this.results_on[i]].element.style.display = 'none';
		}

		this.results_on = [];

		last = this.pages[page] + this.results_per_page;
		for(i = this.pages[page]; (i < last) && (i < this.results.length); i++){
			this.results[i].element.className = 'kwresult_normal' + this.results[i].oe;
			this.results[i].element.style.display = "";
			this.results_on.push(i);
		}

		this.page_previous = this.page_current;
		this.page_current = page;

		this.set_links();
	}


	
	this.next_page = function(){
		if(this.page_current < (this.pages.length - 1)){
			this.show_page(this.page_current + 1);
		}
	}


	
	this.prev_page = function(){
		if(this.page_current > 0){
			this.show_page(this.page_current - 1);
		}
	}


	
	this.kwresult_highlight = function(c){
		this.results[c].element.className = "kwresult_normal" + this.results[c].oe + " kwresult_highlight";		
		
		var tf = dojo.byId("tf" + c);
		if(tf && typeof(tf) !== 'undefined'){
			tf.className = "kwresult_normal" + this.results[c].oe + " kwresult_highlight";
		}
	}


	
	this.kwresult_highlight_off = function(c){
		this.results[c].element.className = "kwresult_normal" + this.results[c].oe;
		
		var tf = dojo.byId("tf" + c);
		if(tf && typeof(tf) !== 'undefined'){
			tf.className = "kwresult_normal" + this.results[c].oe;
		}
	}


	
	this.kwresult_mouseover = function(c){
		this.kwresult_highlight(c);
		if(typeof(localmap) !== 'undefined'){
			mouseover_action(localmap.kw_marker_list[c]);
		}
	}


	
	this.kwresult_mouseout = function(c){
		this.kwresult_highlight_off(c);
		if(typeof(localmap) !== 'undefined'){
			mouseout_action(localmap.kw_marker_list[c]);
		}
	}


	
	this.kwresult_click = function(c){
		if(typeof(localmap) !== 'undefined'){
			click_action(localmap.kw_marker_list[c]);
		}
	}
}




function kwshow_detail (key) {
	if(KW_VARS.mapdone === 0){
		//return;
	}

	KW_VARS.current_page = 'detail';

	KW_VARS.sid = key;
	document.getElementById('search_results').className = "kwresult_hidden";
	document.getElementById('ask-directions').className = 'kwdetail_show';
	document.getElementById('dd_page').className = 'kwresult_hidden';

	var detail_page = document.getElementById('kwdetails');
	var map = dojo.byId("LOCAL_MAP");
	var md  = dojo.byId("results_map_detail");
	var mr  = dojo.byId("results_map_results");

	while (mr.hasChildNodes && mr.childNodes[0]) {
    	mr.removeChild(mr.childNodes[0]);
	}

	while (md.hasChildNodes && md.childNodes[0]) {
    	md.removeChild(md.childNodes[0]);
	}


	md.appendChild(map);

	var detail_div = document.getElementById('detail_page');

	dojo.xhrGet({	url: kw_hostdir + '/cgi/site', 
			content: {mapid: kw_mapid, site: key, place: kw_place, region: kw_region, option: kw_option, region_name: kw_region_name, mapon: 1},
			handleAs: "text",
			timeout: 5000,
        		load: function(response){
					var axel = Math.random()+"";
					var a = axel * 10000000000000;

					detail_div.innerHTML = '<IFRAME SRC="http://fls.doubleclick.net/activityi;src=1160694;type=lowes046;cat=store318;ord=1;num='+ a + '?" WIDTH=1 HEIGHT=1 FRAMEBORDER=0></IFRAME>' + response;

					kw_update_crumbs(2);
					kwresize();
					detail_page.className = 'kwdetail_show';
					detail_div.className = 'kwdetail_show';					
					var dist = dojo.byId("detail_distance");
					if((dist !== null) && (dist !== undefined)){
						dist.innerHTML = '(' + marker_dist[key] + ' Miles)';
					}
	        		},
	        	error: function(response, ioArgs) {
				console.error("HTTP status code: ", ioArgs.xhr.status);
				return response;
				}
			}
			);
}

function clear_place(fn) {
// Clear form field help entries when user clicks on field
	var f = (fn==undefined?document.kwform:document.forms[fn]);
	if(f.region){
		f.region.value = "";
	}
	if (f.place.value == "Street Address, City, State/Province, ZIP/Postal Code" || f.place.value == "Street Address, City, State/Province, ZIP/Postal Code") {
		f.place.value = "";
		//f.place.className = "kw_textbox_focus";
	}
}

function kw_cancel_dd(){
	if(KW_VARS.ddargs){
		KW_VARS.ddpost.cancel();
		return_det(KW_VARS.ddargs.content.site);
		KW_VARS.ddargs = {};
		KW_VARS.ddpost = {};

	}
}

function kwdd (site, fn) {
	site = KW_VARS.sid;
	KW_VARS.current_page = 'dd';
	var f = (fn==undefined?document.kwform:document.forms[fn]);
	var place      = f.place.value;
	var dd_loading = document.getElementById('dd_page_loading');
	var ask_dir    = document.getElementById('ask-directions');
	var dd_div     = document.getElementById('dd_page');

	dd_div.className = "kwdetail_hidden";
	ask_dir.className = "kwdetail_hidden";
	dd_loading.className = "kwdetail_show";
	KW_VARS.ddargs = {
            url: kw_hostdir + '/cgi/directions',
            content: {mapid: kw_mapid, site: site, place: place, region: kw_region, option: kw_option, region_name: kw_region_name, country: kw_mapid},
            load: function(response){
                    dd_div.innerHTML = response;
                    var dds = dojo.byId("dd_script");
                    if(dds != null){
                        dojo.eval(dds.innerHTML);
                    }
                    dd_loading.className = 'kwdetail_hidden';
                    dd_div.className = 'kwdetail_show';
                    kw_update_crumbs(3);
                    kwresize();
                    return false;
                    }
            };	

    KW_VARS.ddpost = dojo.xhrGet(KW_VARS.ddargs);
	return false;
}

function kwdd_reverse (site) {
	site = KW_VARS.sid;
	KW_VARS.current_page = 'dd';
	var place      = document.kwform.place.value;
	var dd_loading = document.getElementById('dd_page_loading');
	var ask_dir    = document.getElementById('ask-directions');
	var dd_div     = document.getElementById('dd_page');

	dd_div.className = "kwdetail_hidden";
	ask_dir.className = "kwdetail_hidden";
	dd_loading.className = "kwdetail_show";
	KW_VARS.ddargs = {
            url: kw_hostdir + '/cgi/directions',
            content: {mapid: kw_mapid, site: site, place: place, region: kw_region, option: kw_option, region_name: kw_region_name, country: kw_mapid, reverse: 'true'},
            load: function(response){
                    dd_div.innerHTML = response;
                    var dds = dojo.byId("dd_script");
                    if(dds != null){
                        dojo.eval(dds.innerHTML);
                    }
                    dd_loading.className = 'kwdetail_hidden';
                    dd_div.className = 'kwdetail_show';
                    kw_update_crumbs(3);
                    kwresize();
                    return false;
                    }
            };	

    KW_VARS.ddpost = dojo.xhrGet(KW_VARS.ddargs);
	return false;
}

function return_sr () {
// Return from detail page or driving directions to search results
	KW_VARS.current_page = 'results';
	document.getElementById('detail_page').className = 'kwdetail_hidden';
	document.getElementById('kwdetails').className = 'kwdetail_hidden';
	document.getElementById('search_results').className = 'kwresult_show';
	document.getElementById('dd_page_loading').className = 'kwdetail_hidden';

	var map = dojo.byId("LOCAL_MAP");
	var md  = dojo.byId("results_map_detail");
	var mr  = dojo.byId("results_map_results");

	while (mr.childNodes[0]) {
    	mr.removeChild(mr.childNodes[0]);
	}

	while (md.childNodes[0]) {
    	md.removeChild(md.childNodes[0]);
	}

	mr.appendChild(map);

	kwresize();
	localmap.remove_line();
	localmap.DD_remove_markers();
	localmap.zoomToExtent(map_bounds);
	if(KW_VARS.DZL !== 0){
		KWMap_zoom(KW_VARS.clat, KW_VARS.clon, KW_VARS.DZL);
	}
	kw_update_crumbs(1);
	return false;
}

function return_det (key) {
// Return from driving directions to detail page
	KW_VARS.current_page = 'detail';
	document.getElementById('dd_page').className = 'kwdetail_hidden';
	document.getElementById('detail_page').className = 'kwdetail_show';
	document.getElementById('kwdetails').className = 'kwdetail_show';
	document.getElementById('ask-directions').className = 'kwdetail_show';
	document.getElementById('search_results').className = 'kwresult_hidden';
	document.getElementById('dd_page_loading').className = 'kwdetail_hidden';

	localmap.remove_line();
	localmap.DD_remove_markers();
	kw_update_crumbs(2);
	kwresize();
	return false;
}

function kw_set_crumb_state(crumb, state){
		var crumb_li;
		var crumb_text;
		var crumb_class;
		var crumb_display = 'inline';
		
		if(state === -1){
			crumb_class = 'kw_crumb_current';
		} else if(state === 1){
			crumb_class = 'kw_crumb_past';
		} else if(state === 2){
			crumb_class = 'kw_crumb_future';
			crumb_display = 'none';
		}

		if(crumb === "kw_crumb_results"){
			if(state === -1){
				crumb_text = 'Search Results';
			} else {
				crumb_text = '<a href="' + kw_hostdir + '" onclick="return return_sr();" style="cursor:pointer;">Search Results</A>&gt;';
			}	
		} else if(crumb === "kw_crumb_detail"){
			if(state === -1){
				crumb_text = 'Store Detail';
			} else {
				crumb_text = '<a href="' + kw_hostdir + '" onclick="return return_det();" style="cursor:pointer;">Store Detail</A>&gt;';
			}	
		} else if(crumb === "kw_crumb_dd"){
			crumb_text = 'Driving Directions';
		} else {
			alert(crumb + " crumb not found");
			return;
		}

		crumb_li = 	dojo.byId(crumb);
		if(crumb_li !== null && (typeof(crumb_li) !== 'undefined') && (typeof(crumb_li) !== 'null')){
			crumb_li.innerHTML = crumb_text;
			crumb_li.className = crumb_class;
			crumb_li.style.display = crumb_display;
		}
}

function kw_update_crumbs(state){
	crumb_ul = dojo.byId("kw_breadcrumbs_list");
	if(typeof(crumb_ul) === 'undefined'){
		return;
	}	
	/* 1 search results
	   2 details
	   3 dd
	*/

	if(state == 1){
		/* results */
		kw_set_crumb_state("kw_crumb_results", -1);
		kw_set_crumb_state("kw_crumb_detail", 2);
		kw_set_crumb_state("kw_crumb_dd", 2);
	} else if(state == 2){
		/* detail */
		kw_set_crumb_state("kw_crumb_results", 1);
		kw_set_crumb_state("kw_crumb_detail", -1);
		kw_set_crumb_state("kw_crumb_dd", 2);
	} else if(state == 3){
		/* dd */
		kw_set_crumb_state("kw_crumb_results", 1);
		kw_set_crumb_state("kw_crumb_detail",  1);
		kw_set_crumb_state("kw_crumb_dd", -1);
	}
}
