//////////////////////////////////
//// API interface functions  ////
//////////////////////////////////


function AddHandler(object, event, handler) {
     $( object ).bind(event,handler);
}

function GetJSONFromAjax(url,callback)
{	//alert(url);
	var r = jQuery.getJSON(url,{},callback);
}

/////////////////////////////////
/////   FirstNeed functions   ///
/////////////////////////////////
String.prototype.replaceAll = function(search, replace){
  return this.split(search).join(replace);
}


function ge(id)
{	return document.getElementById(id);}

function hide(el)
{	el.style.display = 'none';}

function show(el)
{	el.style.display = 'block';}

function MyAlert(str)
{	alert(str);}

function sh(id)
{
	var el = ge(id);
	if(el.style.display!='block'){el.style.display = 'block';}else{el.style.display = 'none';}
}
if(!MTS)
{
var MTS = {	all: {},
	allValues:{}
};
}

/////////////////////////////////
///// Env definition          ///
/////////////////////////////////
function Env(obj)
{	var UAName = navigator.appName;
    var UAVersion = navigator.appVersion;

	if (UAVersion.indexOf('MSIE 6.0')!=-1){this.ie6 = true;}}
var ENV = new Env();
/////////////////////////////////
////MegaTrueSelect definition ///
/////////////////////////////////

function MegaTrueSelect(obj)
{	if(MTS.all[obj.id])
	{		MTS.all[obj.id].destroy();
	}

    if(typeof(MTSLang)!='undefined'){var l = MTSLang;}else{var l = new Array('Ввести','Поиск','--Любой--');}     // langpack

	defObj = {		width : 220,
		listingHeight : 200,
		itemKey : 'id',
		altItemKey : 'id',
		importantLevel : 5,
		importantKey : 'imp',
		autoRender : true,
		autoFillDelay : 200,
		searchable : true,
		searchableWith : 25,
		userValue: false,
		lang : l,
		beNull:false
	};

	this.itemsHTML = '';
	this.itemsVisible = false;
	this.who = 'i am object =)';
	this.altItems = {};
	this.items = {};
	this.value = null;
	this.allValues = {};

	for(var a in defObj)
	{		if(obj[a]==null){this[a] = defObj[a];}	}

	for(var a in obj)
	{		this[a] = obj[a];	}

	MTS.all[this.id] = this;
	this.render();
	this.setTitle('Loading...');
	if(this.itemsLoadFrom){this.loadItems();}

	if(this.autoRender){this.render();}
	return this;
}

MegaTrueSelect.prototype.doItemsHTML = function()
{    var className;
    this.itemsHTML = '';

    if(this.beNull){this.itemsHTML += '<li class="item comand" id="item_'+this.id+'_'+'any'+'" onClick="MTSSetAny(\''+this.id+'\')"><span>'+this.beNull+'</span></li>';}

	for(var i=0;i<this.items.length;i++){		if(this.items[i][this.importantKey]>=this.importantLevel){			className = "important";
		}else{			className = '';
		}
			this.itemsHTML += '<li class="item '+className+'" id="item_'+this.id+'_'+i+'" onClick="MTSSetValue(\''+i+'\',\''+this.id+'\')"><span>'+this.items[i].name+'</span></li>';
	}
    if(this.userValue){this.itemsHTML += '<li class="item comand" onClick="MTSUserValueDialog(\''+this.id+'\')"><span>'+this.lang[0]+'</span></li>';}
	if(this.searchable)
	{		if(this.searchableWith<=this.items.length)
		{
			this.itemsHTML = '<li class="item search" onClick="MTSSearchDialog(\''+this.id+'\')"><span>'+this.lang[1]+'</span></li>'+this.itemsHTML;
		}
	}

	this.itemsHTML = '<div class="itemsBoxR"><ol class="itemsBox hidden" id="il_'+this.id+'">'+this.itemsHTML+'</ol></div>';
}
//  doAltItemsHTML()  - return html for alternative items
MegaTrueSelect.prototype.doAltItemsHTML = function()
{
	this.altItemsHTML = '';
	var name;
	for(var i=0;i<this.altItems.length;i++){
	    var name = this.altItems[i].name;
        if(this.altHighlight)
        {        	if(this.searchFilter)
        	{        		var reT = RegExp(this.altHighlight,"i");
        		if(!reT.test(name)){continue ;}        	}
        	var re=RegExp(this.altHighlight,"i");
        	name = name.replace(re,'<span class="highlight">'+this.altHighlight+'</span>');
        }
			this.altItemsHTML += '<li class="item" id="item_alt_'+i+'_'+this.id+'" onClick="MTSSetAltValue(\''+i+'\',\''+this.id+'\')"><span>'+name+'</span></li>';
	}
	this.altItemsHTML = '<div class="itemsBoxR"><ol class="itemsBox hidden" id="il_alt_'+this.id+'">'+this.altItemsHTML+'</ol></div>';
}

//  onButtonClick()
MegaTrueSelect.prototype.onButtonClick = function(e)
{	var obj = Who(this);
	if(obj.itemsVisible){obj.hideItems();}else{obj.showItems();}}
//hideAll()
MegaTrueSelect.prototype.hideAll = function()
{	for(var i in MTS.all)
	{		if(MTS.all[i])
		{
		   MTS.all[i].hideItems();
		   MTS.all[i].hideAltItems();
		}	}
}
// showItems()
MegaTrueSelect.prototype.showItems = function()
{
	this.hideAll();

	ge('il_'+this.id).style.display = 'block';
	this.itemsVisible = true;
	this.hideAltItems();
}
// showAltItems()
MegaTrueSelect.prototype.showAltItems = function()
{
	ge('il_alt_'+this.id).style.display = 'block';
	this.hideItems();
}
// hideItems()
MegaTrueSelect.prototype.hideItems = function()
{
	ge('il_'+this.id).style.display = 'none';
	this.itemsVisible = false;
}
// hideAltItems()
MegaTrueSelect.prototype.hideAltItems = function()
{
	ge('il_alt_'+this.id).style.display = 'none';
}
// setValue()
MegaTrueSelect.prototype.setValue = function(v,mode)
{
	var prev = this.value;
	this.nowUserInput = false;
	this.setTitle(v.name);
	if(mode=='alt')
	{		this.value = v[this.altItemKey];
		this.valueName = v.name;
	}else{		this.value = v[this.itemKey];
		this.valueName = v.name;
	}
	this.hideItems();
	this.hideAltItems();
	if(this.onSelect && (prev!=this.value)){this.onSelect();}    // fire onSelect event
}
// setTitle()
MegaTrueSelect.prototype.setTitle = function(newTitle)
{
	if(!newTitle){newTitle = this.title;}
	ge('MTStitle_'+this.id).innerHTML = newTitle;
}
// loadItems()
MegaTrueSelect.prototype.loadItems = function()
{	this.autoRender = false;

	MTS['lastREquestFor'] = this.id;
	GetJSONFromAjax(this.itemsLoadFrom,this.onJSONLoad);
}
// loadAltItems()
MegaTrueSelect.prototype.loadAltItems = function()
{
	MTS['lastREquestFor'] = this.id;
	var val = ge('userInput_'+this.id).value;
    if(this.userFieldValue==val){return ;}    // if not change
    this.userFieldValue = val;

    if(this.searchMode)                       // if search
    {    	//this.altItems = thisItems;
    	this.searchFilter = val;
    	this.onJSONLoadAlt(this.items);
    	return ;    }

	GetJSONFromAjax(this.altItemsLoadFrom+encodeURI(this.userFieldValue),this.onJSONLoadAlt);
}

// onJSONLoad()
MegaTrueSelect.prototype.onJSONLoad = function(data)
{
	var obj = MTS.all[MTS['lastREquestFor']];
	obj.items = data;

	obj.render();
	if(obj.defValue){obj.setValue(obj.defValue);}
}
// onJSONLoadAlt()
MegaTrueSelect.prototype.onJSONLoadAlt = function(data)
{
	var obj = MTS.all[MTS['lastREquestFor']];
	obj.altItems = data;
	obj.altHighlight = obj.userFieldValue;
	obj.renderAltItems();
}
// showUserInputField()
MegaTrueSelect.prototype.showUserInputField = function()
{
	  var inputFieldHTML = '<input class="userInput" id="userInput_'+this.id+'">';
	  this.setTitle(inputFieldHTML);
	  ge('userInput_'+this.id).focus();
	  this.nowUserInput = true;
	  this.hideItems();
	  MTS['le'] = this.id;
	  AddHandler(ge('userInput_'+this.id),'keypress',this.onChangeUserField);
}

// setValueFromUserField()  ws
MegaTrueSelect.prototype.setValueFromUserField = function()
{	//alert('userInput_'+this.id);
	var v = new Object;
	var k;
	if(!this.nowUserInput){return ;}else{var v1 = ge('userInput_'+this.id).value;}
	v.name =  v1;
	v[this.itemKey] = v1;
	this.setValue(v);}

//onChangeUserField()
MegaTrueSelect.prototype.onChangeUserField = function(e)
{
  var key = e.which;
  var obj = MTS.all[MTS['le']];
  clearTimeout(obj.timer1);
  if(key==13){obj.setValueFromUserField(); return ;}
  obj.timer1 = setTimeout('MTSLoadAltItems(\''+obj.id+'\')',this.autoFillDelay);
}

//renderAltItems()
MegaTrueSelect.prototype.renderAltItems = function()
{
   this.doAltItemsHTML();
   ge('altBox_'+this.id).innerHTML = this.altItemsHTML;
   ge('il_alt_'+this.id).style.width = this.width+'px';
   this.showAltItems();
}

//goSearch()
MegaTrueSelect.prototype.goSearch = function()
{
	 this.showUserInputField();
	 this.searchMode = true;
}
//destroy()
MegaTrueSelect.prototype.destroy = function()
{
	 ge(this.renderTo).innerHTML = '';
	 if(this.childId && MTS.all[this.childId]){MTS.all[this.childId].destroy();}
	 MTS.all[this.id] = null;
}
//exportValues()
MegaTrueSelect.prototype.exportValues = function()
{
	 MTS.allValues[this.id] = this.value;
	 if(this.byName){MTS.allValues[this.id] = this.valueName;}
	 //alert(MTS.allValues[this.id]);
	 if(this.childId && MTS.all[this.childId])
	 {	 	MTS.all[this.childId].exportValues();
	 }

	 return MTS['allValues'];
}

// render()  - render this oblject
MegaTrueSelect.prototype.render = function()
{
	if(!this.items)
	{		MyAlert('data empty');
		return ;
	}
    //alert('render');
	this.doItemsHTML();
	this.doAltItemsHTML();
	this.waitHTML = '<div class="MTSBoxWait" id="MTSBW_'+this.id+'"><div class="MTStitle" id="MTStitle_'+this.id+'">'+this.title+'</div><div class="chooseButton" id="cb_'+this.id+'"></div></div>';
    this.HTML = '<div class="MTSBox" id="MTSBox_'+this.id+'">';
    this.HTML += this.waitHTML;
    this.HTML += this.itemsHTML;
    this.HTML += '<div id="altBox_'+this.id+'">'+this.altItemsHTML+'</div>';
    this.HTML += '</div>';

	ge(this.renderTo).innerHTML = this.HTML;

	ge('MTSBox_'+this.id).style.width = this.width+'px';   // set size
    ge('il_'+this.id).style.width = this.width+'px';
    ge('MTStitle_'+this.id).style.width = (this.width-45)+'px';
    ge('il_'+this.id).style.maxHeight = (this.listingHeight)+'px';
    if(ENV.ie6){ge('il_'+this.id).style.height = (this.listingHeight)+'px';}
    AddHandler(ge('cb_'+this.id),'click',this.onButtonClick);
    AddHandler(ge('MTStitle_'+this.id),'click',this.onButtonClick);
}


///////////////////////////////////////
/////  other functions            /////
///////////////////////////////////////


// --------------MTSSetValue()----------------
function MTSSetValue(v,objId)
{	obj = MTS.all[objId];
	obj.setValue(obj.items[v]);}

// --------------MTSSetAny()----------------
function MTSSetAny(objId)
{
	obj = MTS.all[objId];
	v = new Object;
	v.name = 0;
	v[obj.itemKey] = 0;
	obj.setValue(v);
	obj.setTitle(obj.lang[2]);
}

function MTSSetAltValue(v,objId)
{
	obj = MTS.all[objId];
	obj.setValue(obj.altItems[v],'alt');
}

function MTSUserValueDialog(objId)
{	obj = MTS.all[objId];
	obj.searchMode = false;
	obj.showUserInputField();}

function MTSSearchDialog(objId)
{
	obj = MTS.all[objId];
	obj.goSearch();
}

function MTSLoadAltItems(id)
{	var obj = Who(id);
	obj.loadAltItems();}


function Who(hz)      // lol
{
	if(hz.who)                 //this
	{
		return hz;
	}else{
		if(MTS.all[hz]){return MTS.all[hz];}  // id
		var s = hz.id.split('_');
		return MTS.all[s[s.length-1]];
	}
}


