/* 

	url 

	id

	callbackMethod  ->  must = AjaxModel.Response

	selValue		->  the value you want to select

	xmlTagName      ->  the name of the tag name in xml page

	selectId        ->  the name of the select menu you want to update it's options

	loadDiv         ->  the id of the loading div

*/





var AjaxModel = new Object();



AjaxModel.RequestModel = function(url, id, callbackMethod, selValue, xmlTagName, selectId, loadDiv, functionToDo)

{

	AjaxModel.selValue    	= selValue;

	AjaxModel.xmlTagName  	= xmlTagName;

	AjaxModel.selectId    	= selectId;

	AjaxModel.loadDiv     	= loadDiv;

	AjaxModel.functionToDo  = functionToDo;

	

	if ( id == '' )

	{	
		$(AjaxModel.selectId).length = 0;
		
		$(AjaxModel.selectId).options[0] = new Option("إختر الماركة",'');
		
		return;
	}



	AjaxModel.request = AjaxModel.createRequestObject();

	AjaxModel.request.onreadystatechange = callbackMethod;

	AjaxModel.request.open("POST", url+id, true);

	AjaxModel.request.send(url);

}



AjaxModel.ResponseModel = function () {

	

	if(AjaxModel.CheckReadyState(AjaxModel.request)){	

		$(AjaxModel.selectId).length = 0;

		

		var	response = AjaxModel.request.responseXML.documentElement;

		var _data = response.getElementsByTagName(AjaxModel.xmlTagName);

		

		if(_data.length == 0){

			$(AjaxModel.selectId).options[0] = new Option("لا توجد طرازات لهذه الماركة",'');
		}

		

		$(AjaxModel.selectId).options[0] = new Option('إختر طراز السيارة', '0');
		$(AjaxModel.selectId).options[0].disabled = 'disabled';
		

		var i;

		for( i = 0 ; i < _data.length ; i++ ){

			var ID   = response.getElementsByTagName('modelId')[i].firstChild.data;

			var NAME = response.getElementsByTagName('modelName')[i].firstChild.data;

			

			$(AjaxModel.selectId).options[i+1] = new Option(NAME, ID);

			

			if (AjaxModel.selValue != null) {

				if (is_array(AjaxModel.selValue)) {   // if the selected values is array

					if(in_array(ID, AjaxModel.selValue)) {

						$(AjaxModel.selectId).options[i+1].selected = true;

					}

				} else {    //  if the selected value is not an array

					if(AjaxModel.selValue == ID) {

						$(AjaxModel.selectId).options[i+1].selected = true;

					}	

				}

			}

		} // for

	}

}



AjaxModel.createRequestObject = function(){

	var objModel;

	if(window.XMLHttpRequest){

		objModel = new XMLHttpRequest();

	}

	else if(window.ActiveXObject){

		objModel = new ActiveXObject("MSXML2.XMLHTTP");

	}

	return objModel;

}



AjaxModel.CheckReadyState = function(objModel){

	if(objModel.readyState < 4) {

		$(AjaxModel.loadDiv).innerHTML = $('loading_clown').innerHTML;

	}

	

	if(objModel.readyState == 4){

		if(objModel.status == 200){
			
			$(AjaxModel.loadDiv).innerHTML = '';
			
			eval(AjaxModel.functionToDo);			

			return true;

		}

		else

		{

			

		}

	}

	

}