﻿// JavaScript Document UTF-8

var myjson = '';
var firstRow = true;
var nbrOfRows = 0;
var height = 50;
var nmax = 10; //max number of rows for expert search.
var expertSearchObject;
var expertSearch;
var domReady;

$(document).ready(function(){
	
	cb = function(j){
		myjson = j;
		var alt = '<option value="valg" selected="selected">V&auml;lj:</option>';
		
		for (var i in j){
			alt += '<option value="' + j[i]['id'] + '">' + j[i]['name'] + '</option>';
		}
		var myselects = '<div id="firstdiv" class="inner">';
		myselects += '<select class="first-select-expert" onchange="populateOperator(this)">'+alt+'</select>';
		myselects += '<select class="second-select-expert"></select>';
		myselects += '</div>';
		
		$("div#outer").html(myselects);
		
		nbrOfRows++;
    
    if (expertSearchObject != undefined) {
      reload(expertSearchObject);
      explain();
    }
	};
	$.getJSON("/sites/default/themes/bilsmart/include/getexpertparameters.php", cb);	
});

var explain_str = "";

function reload(foo) {
  $.ajaxSetup({async:false});
  var firstRow = true;
  var divider = '';
  for (var bar in foo) {
    var id = foo[bar]['id'];
    var op = foo[bar]['op'];
    var val = foo[bar]['val'];
    if (firstRow) {
      firstRow = false;
    } else {
      var $btn = $(".addbutton:last").get();
      addRow($btn);
      greyMeOut($btn);
    }
    var $s1 = $(".inner:last select:first");
    $s1.val(id);
    explain_str += divider;
    divider = ", ";
    explain_str += $('.inner:last select:first :selected').text();
    populateOperator($s1.get()); 
    var $s2 = $s1.next();
    $s2.val(op); explain_str += " " + op;
    if (val) {
      var $s3 = $s2.next(); $s3.val(val);
      explain_str += " " + $('.inner:last select:last :selected').text();
    }
  }
}
function explain() {
  //alert(explain_str);
  $("span#expertSearchExplained").text(explain_str + ".");
}
function populateOperator(x){
	
	var IE6 = (navigator.userAgent.toLowerCase().indexOf('msie 6') != -1) && (navigator.userAgent.toLowerCase().indexOf('msie 7') == -1);
	
	if ($(x).children(":first").val() == 'valg'){
		if(IE6){
			$(x).children(":first").empty();
		}else{
			$(x).children(":first").remove();
		}
	}
	
	var lastdiv = $(".inner:last").get();
	
	for (var i in myjson) {
    // find parameter
		if ($(x).val() == myjson[i]['id']) {
			
			// Populate operator select box
			var alt = '';
			for (var j = 0; j < myjson[i]['operator_list'].length; j++){
				alt += '<option value="' + myjson[i]['operator_list'][j]['name'] 
						+ '">' + myjson[i]['operator_list'][j]['name'] + '</option>';
			}
			$(x).siblings(":first").html(alt);
      
      // remove all elements except the two first
			$(x).siblings().slice(1,5).remove();
			$(x).siblings().slice(1,5).remove();
			
			// Add a listbox if type L
			if (myjson[i]['type'] == 'L') {
				setListBoxValues(myjson[i]['id'], x);
			} else 
      
			// Add a textbox if type T
			if (myjson[i]['type'] == 'T') {
				if ($(x).parent().is(".inner:last-child")) {
					if (nbrOfRows < nmax) {
						$(x).parent().append('<input class="input-expert"></input><input type="image" src="/sites/default/themes/bilsmart/img/addbutton.png" class="addbutton" onclick="addRow(this);greyMeOut(this);"></input><input type="image" src="/sites/default/themes/bilsmart/img/delbutton.png" class="delbutton" onclick="delRow(this)"></input>');
					} else {
						$(x).parent().append('<input class="input-expert"></input><input style="visibility:hidden" type="image" src="/sites/default/themes/bilsmart/img/addbutton.png" class="addbutton" onclick="addRow(this);greyMeOut(this);"></input><input type="image" src="/sites/default/themes/bilsmart/img/delbutton.png" class="delbutton" onclick="delRow(this)"></input>');
					}
				} else {
					$(x).parent().append('<input class="input-expert"></input><input type="image" disabled="true" style="cursor:default" src="/sites/default/themes/bilsmart/img/addbutton_disabled.png" class="addbutton" onclick="addRow(this);greyMeOut(this);"></input><input type="image" src="/sites/default/themes/bilsmart/img/delbutton.png" class="delbutton" onclick="delRow(this)"></input>');
				}
			} else
      
			// Do not add a third element
			if (myjson[i]['type'] == 'B') {
				if ($(x).parent().is(".inner:last-child")) {
					if (nbrOfRows < nmax) {
						$(x).parent().append('<input class="input-expert" style="visibility:hidden"></input><input type="image" src="/sites/default/themes/bilsmart/img/addbutton.png" class="addbutton" onclick="addRow(this);greyMeOut(this);"></img><img src="/sites/default/themes/bilsmart/img/delbutton.png" class="delbutton" onclick="delRow(this)"></input>');
					} else {
						$(x).parent().append('<input class="input-expert" style="visibility:hidden"></input><input style="visibility:hidden" type="image" src="/sites/default/themes/bilsmart/img/addbutton.png" class="addbutton" onclick="addRow(this);greyMeOut(this);"></img><img src="/sites/default/themes/bilsmart/img/delbutton.png" class="delbutton" onclick="delRow(this)"></input>');
					}
				} else {
					$(x).parent().append('<input class="input-expert" style="visibility:hidden"></input><input type="image" disabled="true" style="cursor:default" src="/sites/default/themes/bilsmart/img/addbutton_disabled.png" class="addbutton" onclick="addRow(this);greyMeOut(this);"></input><input type="image" src="/sites/default/themes/bilsmart/img/delbutton.png" class="delbutton" onclick="delRow(this)"></input>');
				}
			}
      
      // parameter found - exit loop
      break;
		}
	}
}

function greyMeOut(x){
	
	$(x).attr("src","/sites/default/themes/bilsmart/img/addbutton_disabled.png");
	$(x).attr("disabled", true);
	$(x).css("cursor", "default");
}


function setListBoxValues(id, x){
	
	callback = function(j){
		var alt = '';
		var myselect = '';
		for (var i in j){
			
			alt += '<option value="' + j[i]['col1'] + '">' + j[i]['col2'] + '</option>';
		}

		if ($(x).parent().is(".inner:last-child")){
			
			if (nbrOfRows < nmax){
				myselect = '<select class="third-select-expert">'+ alt +'</select><input type="image" src="/sites/default/themes/bilsmart/img/addbutton.png" class="addbutton" onclick="addRow(this);greyMeOut(this);"></input><input type="image" src="/sites/default/themes/bilsmart/img/delbutton.png" class="delbutton" onclick="delRow(this)"></input>';
			}else{
				myselect = '<select class="third-select-expert">'+ alt +'</select><input style="visibility: hidden" type="image" src="/sites/default/themes/bilsmart/img/addbutton.png" class="addbutton" onclick="addRow(this);greyMeOut(this);"></input><input type="image" src="/sites/default/themes/bilsmart/img/delbutton.png" class="delbutton" onclick="delRow(this)"></input>';
			}
		}else{
			myselect = '<select class="third-select-expert">'+ alt +'</select><input type="image" disabled="true" style="cursor:default" src="/sites/default/themes/bilsmart/img/addbutton_disabled.png" class="addbutton"  onclick="addRow(this);greyMeOut(this);"></input><input type="image" src="/sites/default/themes/bilsmart/img/delbutton.png" class="delbutton" onclick="delRow(this)"></input>';
		}
		$(x).parent().append(myselect);
	};
	$.getJSON("/sites/default/themes/bilsmart/include/getlistboxvalues.php", {id: id}, callback);
}

function addRow(x){
	if (nbrOfRows < nmax ) {
		nbrOfRows++;

    // find used values of first select-box
    var a = " ";
    $(".first-select-expert option:selected").each(function () {a += this.value + " ";});

    // find first unused value in array of id:s
    var u = 0;
		for (var i in myjson){
      if (a.search(" " + myjson[i]['id'] + " ") < 0) {
        u = myjson[i]['id'];
        break;
      }
		}
    
		var alt = "";
		for (var i in myjson){
			alt += '<option'; 
      if (u == myjson[i]['id']) alt += ' selected';
      alt += ' value="' + myjson[i]['id'] + '">' + myjson[i]['name'] + '</option>';
		}
    
		var myselects = '<div class="inner"><select class="first-select-expert" onchange="populateOperator(this)">'+alt+'</select><select class="second-select-expert"></select></div>';
		$("div#outer").append(myselects);
		if (nbrOfRows > 3) {
			height += 50;
      if (height > 50) {
        // ie6-fix
        $("div#fragment-4-c").height(height + "px");
      }
		}
		populateOperator($(".inner select:last").prev().get());		
	} else {
		//should not reach here since addbutton invisible
	}
}

function delRow(x){
	
	if(nbrOfRows > 3){
    height -= 50;
    if (height > 50) {
      // ie6-fix
      $("div#fragment-4-c").height(height + "px");
    }
  }
	
	nbrOfRows--;
	$(x).parent().remove();
	$(".addbutton:last").attr("src", "/sites/default/themes/bilsmart/img/addbutton.png");
	$(".addbutton:last").attr("disabled", false);
	//$(".addbutton:last").css("margin-left", "20px");
	$(".addbutton:last").css("cursor", "pointer");
	
}
function createJson(){
	
	var json = '[';
	var arr =  new Array(3);		
	arr[0] = "id";
	arr[1] = "op";
	arr[2] = "val";

	for ( var i=0; i < $("div#outer").children().size(); i++){
		
		var element = $("div#outer").children().get(i);
		var nmbrOfElements = $(element).children().size();
		
		if(i > 0){
			json += ',{';
		}else{
			json += '{';
		}
		
		//create json structure on the following syntax:
		//[{"id":2, "op":"är", "val":"AU"},{"id":2, "op":"är", "val":"AU"}]
		
		for( var j=0; j < nmbrOfElements-2; j++){
			var tmp = $(element).children().get(j);
					
			if(j==0){
				json += "\"" + arr[j] + "\":" + $(tmp).val();
			}else{
				json += "\"" + arr[j] + "\":\"" + $(tmp).val() + "\"";
			}
			if(j < nmbrOfElements-3){
				json += ', ';
			}
		}
		
		json += '}';
		
	}
	json += ']';
	
	if (validate(json)){
		doSearch(json);
	}else{
		alert('Textrutans innehåll stämmer inte\nmed det som kan sökas. Var god\nändra och försök igen.');
	}
	
}
function validate(s){
	
	eval( 'a=' + s);  //create an array from the json structure
	
	var tmp = true;
	
	for (var k in a){
		
		var element = $("div#outer").children().get(k);
		var temp = $(element).children().get(2);
		
		var re = myjson[a[k]['id']]['reg_exp'];
		if( re != null){
			
			var str = a[k]['val'];
			
			if(!str.match(re)){
				
				$(temp).attr("style", "border: 2px solid red");
				$(temp).focus();
				tmp = false;
			}else{
				$(temp).removeAttr("style");
			}
		}
	}
	return tmp;
}

function doSearch(json_str){

	var encodedData = Base64.encode(json_str);
	var url = '/searchbyexpert?expertSearch=' + encodedData;
	$("div#loading").css({display: 'block'});
	$("div#loading").bind("ajaxSend", function(){ $(this).show(); });
	window.location.assign(url);
	

}


function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects
	 for(var item in arr) {
	  var value = arr[item];
	 
	  if(typeof(value) == 'object') { //If it is an array,
	   dumped_text += level_padding + "'" + item + "' ...\n";
	   dumped_text += dump(value,level+1);
	  } else {
	   dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
	  }
	 }
	} else { //Strings/Chars/Numbers etc.
	 dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
} 
