$(document).ready(function(){
	
	
	
	
	
	var predictor = new Predictor($("#search_string"), "/proxy/ajax-search-hint.php?q=",'predicter',3);
	var predictorb = new Predictor($("#make_exact_phrase"), "/proxy/ajax-brand-hint.php?q=",'predicter',1);
	
	$("select[name=sortByS]").bind("change", function(){
		window.location = $(this).val();
	});
	$("select[name=sortByS2]").bind("change", function(){
		window.location = $(this).val();
	});
	$("select[name=items_per_pageS]").bind("change", function(){
		window.location = $(this).val();
	});
	$("select[name=items_per_pageS2]").bind("change", function(){
		window.location = $(this).val();
	});

	//-----"From transfer_sites_loading_page.html"-----
	$('.clean_slate_b').hide();
	$('a.leavebtn').click(function(event) {
			
		event.preventDefault();
		
		var link = $(this).attr('href');
		
		var maskHeight = $(document).height();
		var maskWidth = $(window).width();
		
		var winH = $(window).height();
		var ScrollTop = document.body.scrollTop;
		$("#companyname").text(this.rel);
		if (ScrollTop == 0) {
		
			if (window.pageYOffset)
				ScrollTop = window.pageYOffset;
			else
				ScrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
		}
		$("#companyname").text(this.rel);
		
		$("#leavingpopup").css('top',  winH/2-$("#leavingpopup").height()/2 +ScrollTop );
		
		//Set heigth and width to mask to fill up the whole screen
		$('#mask').css({'width':maskWidth,'height':maskHeight});
		$('#mask').css('position', 'absolute');
		$('#mask').css('top', 0);
		$('#mask').css('left', 0);
		
		//transition effect		
		$('#mask').fadeIn(1000);	
		$('#mask').fadeTo("slow",0.8);
		// black bkg done
		
		$('#leavingpopup').css('display', 'block');
		$('#leavingpopup').show();
		var url = this.href;
	
		$.ajax({
			url: url,
			cache: false,
			success: function(response){
				//location.href = response;			//if want to open link in same window
				child1=window.open(response, '_blank');	//if want to open link in new window
				if (!child1) {   
				$('#delaycountdown').html(' 5 ');
				$('.clean_slate_b').show();
			
				setTimeout("$('#delaycountdown').html(' 4 ');",1000);
				setTimeout("$('#delaycountdown').html(' 3 ');",2000);
				setTimeout("$('#delaycountdown').html(' 2 ');",3000);
				setTimeout("$('#delaycountdown').html(' 1 ');",4000);
				setTimeout("location.href = '"+response+"';",4000);
				
					}else{
						setTimeout("$('#leavingpopup').hide();",2000);
						setTimeout("$('#mask').hide();",2000);
					}
			}
			
		});	
		
	setTimeout("$('#leavingpopup').hide();",2000);
	setTimeout("$('#mask').hide();",2000);
	});
	
	//-----End of "From transfer_sites_loading_page.html"-----
			
document.search_form.search_string.focus();

	$("span.attr_name").click(function(){
					$(this).next("ul").slideToggle("slow");			 
					return true;
				});

			
			
										//menu configuration
							var MenuConfig = function(){
								this.hideTimeout = 100;
								this.itemHeight = 22;
								this.sTimeout = 50;
								this.sInterval = 50;
								this.leftMargin = -5;

								//menu scroll
								this.scrollDuration = 400;
								this.scrollStep = 10;
								this.scrollDelay = 0;
								this.isdown = false;

								//configurtation options
								this.headerHeight = 29;
								if (document.search_form.menuOffset.value== -110){ this.headerTop = -110; }else{ this.headerTop = -52; }
							
								// ts -110; micro -52
								//current item reference
								this.left = [];
								this.top = [];
								this.top[0] = 0;
								this.topOffset = 0;
								this.leftOffset = -10;
								this.currentDiv = [];
								this.isover = [];
								this.headerDiv = [];

								//div position, width, z-index
								this.pos = {top:0, left:0};
								this.zIndex = 0;

								//==========================================================
								//Methods to show header with corners
								//==========================================================
								this.setCorners = function() {
									curvyCorners({
										tl: {
											radius: 10
										},
										tr: {
											radius: 10
										},
										bl: {
											radius: 0
										},
										br: {
											radius: 0
										},
										antiAlias: true
									},
									".cmConID");
								};

								this.showHeader = function(e){
							
								
									document.search_form.search_string.blur();
									if(typeof(this.headerDiv[parseInt(e.substring(4))]) == 'undefined' || this.headerDiv[parseInt(e.substring(4))] == null){
									
										var header = $(document.createElement("div"))
										.attr('class', 'ts-menu-centre')
										.height(21)
										.width($("#" + e).width())
										.css({
											//'left': this.leftOffset,
											'left': '0px',
											'top': $("#" + e).position().top + this.headerTop + 92,
											'position':'absolute'
										})
										.addClass("cheader")
										
										.html('<span class="ts-menu-left"></span><span class="ts-menu-centre-pos">'+'<a href="' + $("#" + e).find("a").get(0).href + '">' + $("#" + e).find("a").first().html() + '</a></span><span class="ts-menu-right"></span>');
										$("#" + e).append(header);
									//	this.setCorners();
										this.headerDiv[parseInt(e.substring(4))] = header;
									}
									this.headerDiv[parseInt(e.substring(4))].show();
								};

								this.hideHeader = function(hide){
									if(hide){
										document.search_form.search_string.focus();
										for(var i = 0; i < this.headerDiv.length; i++){
											if(typeof(this.headerDiv[i]) !== 'undefined'){
												$(this.headerDiv[i]).hide();
											}
										}
									}
								};

								//==========================================================
								//Methods to highlight selected li or parent li of divs
								//==========================================================
								this.highlightLi = function(e){
									if(this.getLevel(e) == 0){
										$("#" + e.substring(4)).css('background-color',"#aeaeae");
										return;
									}
									$("#" + e.substring(4)).css('background-color',"#818181");
								};

								this.clearLi = function(e){
									if(this.getLevel(e) == 0){
										$("#" + e.substring(4)).css('background-color',"transparent");
										return;
									}
									$("#" + e.substring(4)).css('background-color',"#aeaeae");
								};
								//==========================================================
								//Methods to show /hide up/down arrows
								//==========================================================

								this.showHideMenu = function(items, tmid){
									if(tmid.scrollTop() + tmid.height() >= (items.length * config.itemHeight)){
										$(tmid).parent().find(".down").css('opacity',0.2);//.hide();
										clearInterval(config.sInterval);
										config.sInterval = null;
									}else{
										$(tmid).parent().find(".down").css('opacity',1.0);
									}
									if(tmid.scrollTop() == 0){
										$(tmid).parent().find(".up").css('opacity',0.2);//.hide();
										clearInterval(config.sInterval);
										config.sInterval = null;
									}else{
										$(tmid).parent().find(".up").css('opacity',1.0);
									}
								};

								this.moveMenu = function(target, direction, event){
									var tmid = $(target).parent().find("div.mid");
									clearInterval(this.sInterval);
									this.isdown = false;
									switch(event){
										case 'down':
									
											this.isdown = true;
											switch(direction){
												case 'c8 down':
												
													tmid.animate({
														scrollTop: tmid.scrollTop() + (config.scrollStep * config.itemHeight)
													}, config.scrollDuration, 'linear',
													function(){
														config.showHideMenu(tmid.find("li"), tmid);
													});
													
													config.sInterval = setInterval(function(){
														
														tmid.animate({
															scrollTop: tmid.scrollTop() + (config.scrollStep * config.itemHeight)
														}, config.scrollDuration, 'linear',
														function(){
															config.showHideMenu(tmid.find("li"), tmid);
															if(!config.isdown){
																clearInterval(config.sInterval);
																config.sInterval = null;
																return;
															}
														});
													}, config.scrollDuration + config.scrollDelay);
													break;
												case 'c5 up':
													tmid.animate({
														scrollTop: tmid.scrollTop() - (config.scrollStep  * config.itemHeight) > 0 ? tmid.scrollTop() - (config.scrollStep  * config.itemHeight) : 0
													}, config.scrollDuration,'linear',
													function(){
														config.showHideMenu(tmid.find("li"), tmid);
													});
													config.sInterval = setInterval(function(){
														tmid.animate({
															scrollTop: tmid.scrollTop() - (config.scrollStep  * config.itemHeight) > 0 ? tmid.scrollTop() - (config.scrollStep  * config.itemHeight) : 0
														}, config.scrollDuration,'linear',
														function(){

															config.showHideMenu(tmid.find("li"), tmid);
															if(!config.isdown){
																clearInterval(config.sInterval);
																config.sInterval = null;
																return;
															}
														});
													}, config.scrollDuration + config.scrollDelay);
													break;
											}
											break;
										case 'up':
											this.isdown = false;
											config.showHideMenu(tmid.find("li"), tmid);
											break;
									}
								};

								//==========================================================
								//Methods to show /hide drop down divs
								//==========================================================
								//show div
								this.showDiv = function(e, hide){
									//show all the parents
									if(hide){
										var l = this.getLevel(e);
										for(var i = 0; i <= l; i++){
											if(this.currentDiv[i] !== null && this.currentDiv[i].length !== 0){
												if(i > 0){
                                                                                                    //check for right margin
                                                                                                    this.currentDiv[i].css('left', this.left[i - 1] + this.leftMargin);
												}
												this.currentDiv[i].css('z-index',i);
												this.currentDiv[i].show();
                                                                                                if(i > 0){
                                                                                                    if((this.currentDiv[i].position().left + this.currentDiv[i].width() - $("#container").width()) > 0){
                                                                                                            this.currentDiv[i].css('left', this.currentDiv[i].position().left - this.currentDiv[i - 1].width() - this.currentDiv[i].width() + 10);
                                                                                                    }
                                                                                                }
                                                                                                //console.log(this.currentDiv[i].position().left);
												//add li class
												this.highlightLi(this.currentDiv[i].attr('id'));
												this.left[i] = parseFloat(this.currentDiv[i].position().left)
													+ parseFloat(this.currentDiv[i].width());
											}
											if(l == i){
												//this.currentDiv[i].parent().find("div.mid").animate({scrollTop:0},10);
											}
										}
										if(this.getLevel(e) == 0){
											this.showHeader(e);
										}

									}
								};

								this.hideDivAll = function(){
									for(var i = this.isover.length; i >= 0; i--){
										if(typeof(this.currentDiv[i]) !== 'undefined'
											&& this.currentDiv[i] !== null
											&& this.currentDiv[i].length !== 0){
											//remove li class
											this.clearLi(this.currentDiv[i].attr('id'));
											this.currentDiv[i].hide();
										}
									}
								};
								//hide div
								this.hideDiv = function(e, hide){
									//if(hide){
									var i = this.getLevel(e) + (hide ? 0: 1);
									if(typeof(this.currentDiv[i]) !== 'undefined'
										&& this.currentDiv[i] !== null
										&& this.currentDiv[i].length !== 0){
										//remove li class
										this.clearLi(this.currentDiv[i].attr('id'));
										this.currentDiv[i].hide();
									}
									//}
								};

								//==========================================================
								//Utility method to get depth from id of div/li
								//==========================================================
								//get menu depth
								this.getLevel = function(e){
									var s = e.split("_");
									if(s[0] == "div"){
										return s.length - 3;
									}
									return s.length - 2;
								};


								//==========================================================
								//Methods to get/set isover cache for items
								//==========================================================
								//get over
								this.getIsOver = function(id){
									return this.isover[id == null || typeof(id) == 'undefined' ? 0 : this.getLevel(id)];
								};

								//set over
								this.setIsOver = function(id, value){
									//this.isover[this.getLevel(id)] = value;
									if(value == true){
										for(var i = 0;  i < this.getLevel(id); i++){
											this.isover[i] = value;
										}
									}else{
										this.isover[this.getLevel(id)] = value;
									}
								};


								//==========================================================
								//Methods to get/set currentDiv cache for items
								//==========================================================
								//get div
								this.getDiv = function(id){
									return this.currentDiv[id == null || typeof(id) == 'undefined' ? 0 : this.getLevel(id)];
								};

								//set div
								this.setDiv = function(id, div, hide){
									if(hide){
										var i = this.getLevel(id);
										if(typeof(this.currentDiv[i]) !== 'undefined'
											&& this.currentDiv[i] !== null
											&& this.currentDiv.length !== 0){
											this.clearLi($(this.currentDiv[i]).attr('id'));
											$(this.currentDiv[i]).hide();
											this.currentDiv[i] = null;
										}
										if(div == null || div.length == 0){
											this.currentDiv[i] = null;
											return;
										}

										this.currentDiv[i] = div;
										//this.currentDiv[i].css('top',$("#" + id).position().top + this.headerHeight + (i == 0 ? 0 : this.topOffset));
										//console.log($("#" + id).position().top + this.headerHeight + (i == 0 ? 0 : this.topOffset));
										//show header is this is the fist div of the drop down
										
										if(i == 0){
											this.top[i] = (($("#" + id).position().top + this.headerHeight)-8) ;
											this.topOffset = $("#" + id).position().top;
											this.leftOffset = $("#" + id).position().left;
											this.showHeader(id);
										}else{
											this.top[i] = $("#" + id).position().top  + this.top[i-1]+2;
										}
										
									
										
										this.currentDiv[i].css('top',this.top[i]);
										this.currentDiv[i].css('left',this.leftOffset);
									}
								};
							};
							var config = new MenuConfig();

							var CallShow = function(id, hide){
								clearTimeout(config.sTimeout);
								config.setDiv(id, $("#div_" + id), hide);
								config.setIsOver(id, true);
								if(config.getLevel(id) == 0 && hide == true){
									config.hideDivAll();
									config.hideHeader(hide);
								}else{
									config.hideDiv(id, hide);
								}
								config.showDiv(id, hide);
							};

							var CallHide = function(id, hide){
								config.setIsOver(id,false);
								config.sTimeout = setTimeout(function(){
									if(!config.getIsOver(id)){
										config.hideDivAll();
										config.hideHeader(true);
									}
								},config.hideTimeout);
							};

							var CallMove = function(e, button){
								config.moveMenu(e.currentTarget, e.currentTarget.className, button);
							};

							$("div.up, div.down").mousedown(function(e){
								CallMove(e,'down');
							}).mouseup(function(e){
								CallMove(e,'up');
							});

							$("div.up, div.down").mouseenter(function(e){
								CallShow($(e.currentTarget).attr('tag'), false);
							});
							$("div.up, div.down").mouseleave(function(e){
								CallHide($(e.currentTarget).attr('tag'), false);
							});
							$("li.sub,ul.tcmenu>li").mouseenter(function(e){
								CallShow($(e.currentTarget).attr('id'), true);
							});
							$("li.sub,ul.tcmenu>li").mouseleave(function(e){
								CallHide($(e.currentTarget).attr('id'), true);
							});
						});
						
						
						
						
						function loadsearchfields(){ //for search.php: only show in the query string nessesary/filled out fields
							
							getstring = "";
							first = true; //for AddPieces to determine if values have been added to the string yet or not (see code dealing with '&')
							if (document.search_form.search_string.value.length<1){
								alert('You must enter a search term.');
								document.search_form.search_string.focus();
								return false;
							}
							
							if (document.getElementById("company")){
							if (document.search_form.company.value.length > 0){ //if the 'company' field is set, add it and the hidden field 'company_list' to the query string
								getstring += "company=" + encodeURI(document.search_form.company.value) + "&company_list=" + encodeURI(document.search_form.company_list.value);
								first = false;
							}
							}
						
							pieces = new Array (
												"max_price", 
												"min_price",
												"search_string"
												);
				
							getstring += AddPieces(pieces, first); //add other fields only if they contain values

							location.href ="/search/search.php?" + getstring;
							
							return false;
						}
						function simpleloadsearchfields(){ //for search.php: only show in the query string nessesary/filled out fields
							
							getstring = "";
							first = true; //for AddPieces to determine if values have been added to the string yet or not (see code dealing with '&')
							if (document.search_form.search_string.value.length<1){
								alert('You must enter a search term.');
								document.search_form.search_string.focus();
								return false;
							}
						
							pieces = new Array ("search_string"
												//"top_category"
												);
					
							getstring += AddPieces(pieces, first); //add other fields only if they contain values

						

							location.href ="/search/search.php?" + getstring;
							
							return false;
						}
						function onsubmitsearchemptycheck(){
							if (document.search_form.search_string.value.length<1){
								
								return false;
							}else{
								
								return true;
								}
							}
						
						//-----------------------------------------------------------------------------------------------------------
						//AddPieces
						//-----------
						//add field values named in array 'potential_pieces' to the get_str_value string only if they contain values;
						//if first == false an '&' will be added at the beggining of the string; get_str_value is returned.
						//-----------------------------------------------------------------------------------------------------------
						function AddPieces (potential_pieces, first) { 
							
							get_str_value = "";
							pieces = new Array();
							names = new Array();
							num_p = 0;
							
							for (i = 0; i < potential_pieces.length; i++) { //determine which pieces to add
								
								var potential_piece = document.getElementById(potential_pieces[i]);
								
								if (potential_piece.value != 0) { //if this field is not empty
									
									if (num_p == 0 && first == false) { //if this is the first filled out field in this function but not the first filled out field
										get_str_value = "&";
									}
									pieces[num_p] = potential_piece; //add to the list of filled out fields
									names[num_p] = potential_pieces[i]; //save its name as well
									num_p++;
								} 
							}
							
							for (i = 0; i < pieces.length; i++) { //add pieces
		
								get_str_value += names[i] + "=" + encodeURIComponent(pieces[i].value);
									
								if (i != (pieces.length - 1)) { //if this is not the last piece
									get_str_value += "&";
								}
							}
							
							return get_str_value; 
						}
						
function list_mode_switch(){
if (document.modeswitcher.list_mode_url.value==1){
	window.open(document.modeswitcher.list_mode_url.value,"_self");
	}
}
