//function failedAjax_handler(cState_obj, href_value) {
function c_failedAjax_handler(href_value) {
	//if( typeof(cState_obj) == 'object') {
		//cState_obj.failedAjax( href_value );
		//}
	curState.failedAjax( href_value );
	}
//проверяет наличие в массиве arr значения needle
function in_array( arr, needle ) {
	for (var key in arr) {
		if (arr[key] == needle) {
			return true;
			}
		}
	return false;
	}
	

var dopParams = function( dop_params ) {
	this.giid 	= -1;
	this.spiid 	= -1;
	this.npn 	= -1;
	this.ppn 	= -1;
	this.gia 	= -1;
	this.dtl 	= '';
	if (typeof( dop_params ) == 'object') {
		for (var key in dop_params) {
			if ( ( typeof(this[key]) == 'number' && typeof(dop_params[key]) == 'number' && dop_params[key] >= 0 ) || ( typeof(this[key]) == 'string' && typeof(dop_params[key]) == 'string' ) || ( key=='dtl' && typeof( dop_params[key] ) == 'number' ) ) {
				this[key] = dop_params[key];
				}
			}
		}
	}
dopParams.prototype.change = function( dop_params ) {
	/*if (typeof( dop_params ) == 'object') {
		for (var key in dop_params) {
			if ( ( typeof(this[key]) == 'number' && typeof(dop_params[key]) == 'number' && dop_params[key] >= 0 ) || ( typeof(this[key]) == 'string' && typeof(dop_params[key]) == 'string' ) ) {
				this[key] = dop_params[key];
				}
			}
		}*/
	/* изменено 20:55 23.09.2008 */
	if (typeof( dop_params ) == 'object') {
		for (var key in dop_params) {
			if ( ( typeof(this[key]) == 'number' && typeof(dop_params[key]) == 'number' ) || ( typeof(this[key]) == 'string' && typeof(dop_params[key]) == 'string' ) ) {
				this[key] = dop_params[key];
				}
			}
		}
	}
dopParams.prototype.myToString = function( ) {
	var for_ret=' dop_params={';
	for (var key in this) {
		if( typeof(this[key]) != 'function' ) {
			for_ret = for_ret+'\''+key+'\' : \''+this[key]+'\' ,';
			} else alert( typeof(this[key]) );
		}
	for_ret = for_ret+' }';
	return for_ret;
	}
dopParams.prototype.getGET = function( dop_params ) {
	var for_ret = '';

	for (var key in this) {
		if (typeof(this[key]) == 'number') {
			if (this[key] >= 0) {
				for_ret = for_ret+'&'+key+'='+this[key];
				}
			}
		if (typeof(this[key]) == 'string') {
			if (this[key] != '') {
				for_ret = for_ret+'&'+key+'='+this[key];
				}
			}
		}
	return for_ret;
	}
	

var cState = function( ) {
	this.refresh_from_iframe = false;

	this.firstRun			= true;
	this.firstRunSelectors	= true;
	
	this.obj_type	= '';
	this.obj_id		= 0;
	
	this.catalog_states 	= new Array('catalog', 'novelties', 'direction', 'brand', 'product');
	this.trade_marks_states = new Array('trade_marks', 'main_brand');
	
	this.timeout_value				= 10 * 1000;
	this.timeout_id					= null;
	this.error_div_id				= 'failedAjax';
	this.error_href_id				= 'link_in_failedAjax';
	this.gallery_window_div_id		= 'catalog_gallery_window';
	this.sp_gallery_window_div_id	= 'sp_catalog_gallery_window';
	
	this._curHash = '';
	
	this.dop_params = new dopParams( {} );
	
	this.init_obj_type		= '';
	this.init_obj_id		= 0;
	this.init_dop_params	= new dopParams( {} );
	}
cState.prototype.init = function( obj_type, obj_id, dop_params ) {
	var need_changeTo = false;
	var new_obj_type = '';
	var new_obj_id = 0;
	var new_dop_params = {};
	
	this.obj_type 	= obj_type;
	this.obj_id		= obj_id;
	this.dop_params.change( dop_params );
	
	this.init_obj_type = this.obj_type;
	this.init_obj_id = this.obj_id;
	this.init_dop_params = new dopParams ( this.dop_params );
	
	this._curHash = location.hash;
	
	if (location.hash.indexOf('catalog:') != -1) {
		var tmp_obj = this.parse_anchor( location.hash );
		
		new_obj_type	= tmp_obj.new_obj_type;
		new_obj_id		= tmp_obj.new_obj_id;
		new_dop_params	= tmp_obj.new_dop_params;
		
		if (new_obj_type != '') {
			need_changeTo = true;
			}
		else {
			document.getElementById( "catalog_top_menu" ).style.visibility = "visible";
			document.getElementById( "catalog_top_image" ).style.visibility = "visible";
			document.getElementById( "catalog_left_menu" ).style.visibility = "visible";
			document.getElementById( "catalog_main_content" ).style.visibility = "visible";
			document.getElementById( "catalog_right_menu" ).style.visibility = "visible";
			if (this.dop_params.gia > 0) {
				this.showGallery( true );
				}
			this.firstRun = false;
			}
		}
	else {
		document.getElementById( "catalog_top_menu" ).style.visibility = "visible";
		document.getElementById( "catalog_top_image" ).style.visibility = "visible";
		document.getElementById( "catalog_left_menu" ).style.visibility = "visible";
		document.getElementById( "catalog_main_content" ).style.visibility = "visible";
		document.getElementById( "catalog_right_menu" ).style.visibility = "visible";
		if (this.dop_params.gia > 0) {
			this.showGallery( true );
			}
		if (this.dop_params.spiid > 0) {
			this.showSpGallery( true );
			}
		this.firstRun = false;
		}
		
	/* history init */
	if($.browser.msie) {		
		if (this._curHash == '') {
			this._curHash = '#'; // а нужно ли оно?
		}
		
		// add hidden iframe for IE
		$("body").prepend('<iframe id="jQuery_history" style="display: none;"></iframe>');
		this.refreshHistory( '' );
	}
	setInterval(this._check, 500);
	/* [end] history init */
	
	if ( need_changeTo ) {
		new_dop_params = new dopParams( new_dop_params );
		this.changeTo(new_obj_type, new_obj_id, new_dop_params, location.href);
		}
	}
cState.prototype.parse_anchor = function( lhash ) {
	var new_obj_type = '';
	var new_obj_id = 0;
	var new_dop_params = {};
	
	var hash_array = lhash.substr(9).split('&', 15);
	for (var key in hash_array) {
		var param_array = hash_array[key].split('=', 2);
		if (param_array.length == 2) {
			switch (param_array[0]) {
				case 'type':
					new_obj_type = param_array[1];
					break;
				case 'id':
					var parsed_value = parseInt( param_array[1] );
					new_obj_id = parsed_value == param_array[1] ? parsed_value : param_array[1];
					break;
				default:
					var parsed_value = parseInt( param_array[1] );
					new_dop_params[ param_array[0] ] = parsed_value == param_array[1] ? parsed_value : param_array[1];
					break;
				}
			}
		}
	return {'new_obj_type':new_obj_type , 'new_obj_id':new_obj_id , 'new_dop_params':new_dop_params};
	}
cState.prototype._check = function( ) {	
	if ( curState.timeout_id == null ) {
		var new_obj_type	= '';
		var new_obj_id		= 0;
		var new_dop_params	= {};
		
		if($.browser.msie) {
			var ihistory = $("#jQuery_history")[0];
			var iframe = ihistory.contentDocument || ihistory.contentWindow.document;
			var current_hash = iframe.location.hash;
			if(current_hash != curState._curHash) {
				if ( current_hash !="#" && current_hash != "" ) {
					var tmp_obj		= curState.parse_anchor( current_hash );
					new_obj_type	= tmp_obj.new_obj_type;
					new_obj_id		= tmp_obj.new_obj_id;
					new_dop_params	= tmp_obj.new_dop_params;
					/*
					var new_dop_params_str = "";
					for (var key in new_dop_params) {
						if ( typeof new_dop_params[key] != "function" ) {
							new_dop_params_str += key + ":" + new_dop_params[key] + ", ";
							}
						}
					new_dop_params_str = "{ " + new_dop_params_str + "}";
					console.log(new_obj_type, new_obj_id, new_dop_params_str);
					/**/
					}
				else {
					new_obj_type	= curState.init_obj_type;
					new_obj_id		= curState.init_obj_id;
					new_dop_params	= curState.init_dop_params;
					}
				
				var linkForErrorDiv = location.hash;
				linkForErrorDiv_indexOf = linkForErrorDiv.indexOf("#");
				if (linkForErrorDiv_indexOf >= 0) {
					linkForErrorDiv = linkForErrorDiv.substring(0, linkForErrorDiv_indexOf);
					}
				
				// !!!
				new_dop_params = new dopParams( new_dop_params );
				
				curState.refresh_from_iframe = true;
				curState.changeTo(new_obj_type, new_obj_id, new_dop_params, linkForErrorDiv+current_hash);
				
				curState._curHash = current_hash;
				}
			}
		else {
			var current_hash = location.hash;
			if(current_hash != curState._curHash) {
				if ( current_hash !="#" && current_hash != "" ) {
					var tmp_obj		= curState.parse_anchor( current_hash );
					new_obj_type	= tmp_obj.new_obj_type;
					new_obj_id		= tmp_obj.new_obj_id;
					new_dop_params	= tmp_obj.new_dop_params;
					}
				else {
					new_obj_type	= curState.init_obj_type;
					new_obj_id		= curState.init_obj_id;
					new_dop_params	= curState.init_dop_params;
					}
				
				
				var linkForErrorDiv = location.hash;
				linkForErrorDiv_indexOf = linkForErrorDiv.indexOf("#");
				if (linkForErrorDiv_indexOf >= 0) {
					linkForErrorDiv = linkForErrorDiv.substring(0, linkForErrorDiv_indexOf);
					}
				
				// !!!
				new_dop_params = new dopParams( new_dop_params );
				
				curState.refresh_from_iframe = true;
				curState.changeTo(new_obj_type, new_obj_id, new_dop_params, linkForErrorDiv+current_hash);
				
				curState._curHash = current_hash;
				}
			}
		}
	}
cState.prototype.resetDop_params = function( ) {
	delete this.dop_params;
	this.dop_params = new dopParams( {} );
	}
cState.prototype.showGallery = function( no_work_with_anchor ) {

	if(this.dop_params.spiid >= 0) {
		this.hideSpGallery( );
		}
	
	this.g_positioningCenter( );
	
	this.dop_params.gia = 1;
	if( no_work_with_anchor !== true ) {
		this.refreshAnchor( );
		this._curHash = this.getAnchor();
		this.refreshHistory( '' );
		}
	
	return true;
	}
cState.prototype.showSpGallery = function( no_work_with_anchor ) {

	if (this.dop_params.gia >= 0) {
		this.hideGallery( );
		}

	this.sp_g_positioningCenter( );
	
	//this.dop_params.gia = 1;
	if( no_work_with_anchor !== true ) {
		this.refreshAnchor( );
		this._curHash = this.getAnchor();
		this.refreshHistory( '' );
		}
	
	return true;
	}
cState.prototype.hideGallery = function( no_work_with_anchor ) {
	document.getElementById('catalog_gallery_window').style.display = "none";
	
	this.dop_params.gia = -1;
	if( no_work_with_anchor !== true ) {
		this.refreshAnchor( );
		this._curHash = this.getAnchor();
		this.refreshHistory( '' );
		}

	return true;
	}
cState.prototype.hideSpGallery = function( no_work_with_anchor ) {
	document.getElementById('catalog_sp_gallery_window').style.display = "none";
	
	if( no_work_with_anchor !== true ) {
		this.dop_params.spiid = -1;
		this.refreshAnchor( );
		this._curHash = this.getAnchor();
		this.refreshHistory( '' );
		}

	return true;
	}
cState.prototype.failedAjax = function( href_value ) {
	if( this.timeout_id != null ) {
		var error_div = document.getElementById(this.error_div_id);
		
		error_div.style.display = "block";
		document.getElementById(this.error_href_id).href = href_value;
		
		WP_positioningCenter(error_div,0,0,0,0);
		}
	
	//изменение курсора на нормальный
	document.body.style.cursor = "default";
	$.cssRule("a", "cursor:pointer");
	}
cState.prototype.g_positioningCenter = function( ) {
	$(document).ready(function () {
		//ACHTUNG!
		document.getElementById('catalog_gallery_window').style.display = "block";
		WP_positioningCenter(document.getElementById('catalog_gallery_window'),0,0,0,0);
		});
	}
cState.prototype.sp_g_positioningCenter = function( ) {
	$(document).ready(function () {
		//ACHTUNG!
		document.getElementById('catalog_sp_gallery_window').style.display = "block";
		WP_positioningCenter(document.getElementById('catalog_sp_gallery_window'),0,0,0,0);
		});
	}
cState.prototype.successAjax = function( obj_type, obj_id, dop_params, title ) {
	var cur_anchor = this.getAnchor();
	var was_first_run = false;
	
	if ( this.firstRun ) {
		document.getElementById( "catalog_top_menu" ).style.visibility = "visible";
		document.getElementById( "catalog_top_image" ).style.visibility = "visible";
		document.getElementById( "catalog_left_menu" ).style.visibility = "visible";
		document.getElementById( "catalog_main_content" ).style.visibility = "visible";
		document.getElementById( "catalog_right_menu" ).style.visibility = "visible";
		was_first_run = true;
		this.firstRun = false;
		}
	
	//изменение курсора на нормальный
	document.body.style.cursor = "default";
	$.cssRule("a", "cursor:pointer");
	
	
	//изменение основной менюшки
	if (in_array(this.catalog_states, obj_type) && !in_array(this.catalog_states, this.obj_type)) {
		H_getImgSrc(SP_name_lat, "unhard");
		SP_name_lat = "production";
		H_getImgSrc(SP_name_lat, "hard");
		}
	else if (in_array(this.trade_marks_states, obj_type) && !in_array(this.trade_marks_states, this.obj_type)) {
		H_getImgSrc(SP_name_lat, "unhard");
		SP_name_lat = "brands";
		H_getImgSrc(SP_name_lat, "hard");
		}
	
	//изменяем текущее состояние
	if (this.obj_type != obj_type || this.obj_id != obj_id) {
		this.resetDop_params();
		}
	if (typeof(dop_params.gia) == 'undefined') {
		this.dop_params.gia = -1;
		}	
	this.obj_type = obj_type;
	this.obj_id	= obj_id;
	
	/* изменено 21:04 23.09.2008*/
	//this.dop_params.change( dop_params );
	this.dop_params = new dopParams( dop_params );
	
	var new_anchor = this.getAnchor();
	
	
	//$("#debug_div").prepend( "<p><br/><b>I'm in curState::successAjax</b> :\n "+new_anchor+" ==? "+cur_anchor + "</p>");
	if ( !this.refresh_from_iframe && !was_first_run ) {
		if ( new_anchor != cur_anchor ) {
			this._curHash = new_anchor;
			this.refreshAnchor( );
			/* history */
			if ($.browser.msie) {
				this.refreshHistory( title );
				//$("#debug_div").prepend( "<p><br/>\t this._curHash="+this._curHash+" , iframe.location.hash="+iframe.location.hash + "</p>" );
				}
			/* [end] history */
			}
		}
	else {
		this.refresh_from_iframe = false;
		if ($.browser.msie) {
			this.refreshAnchor( );
			var iframe = $("#jQuery_history")[0].contentWindow.document;
			if (title != "") {
				iframe.title = title;
				}
			}
		}
	
	
	if (typeof(title) == 'string' && title != '' ) {
		document.title = title;
		}
		
		
	if (this.dop_params.gia > 0) {
		this.showGallery( true );
		}
	
	if (this.dop_params.spiid > 0) {
		this.showSpGallery( true );
		}
	else if ( document.getElementById('catalog_sp_gallery_window') ) {
		this.hideSpGallery( true );
		}
		
	
	// обработка списков при наличии якоря
	//if ( location.hash.indexOf('catalog?') != -1 ) {
		
		$(document).ready(function () {
		//	alert( "2nd selectors" );
			/*$("#c_select_directions").show();
			$("#c_select_directions").selectbox();
			$("#c_select_brands").show();
			$("#c_select_brands").selectbox();
			$("#c_select_products").show();
			$("#c_select_products").selectbox();*/
			curState.firstRunSelectors = false;
			});
	//	}
	//убиваем timeout, скрываем окошко с ошибкой
	if (this.timeout_id != null) {
		window.clearTimeout( this.timeout_id );
		this.timeout_id = null;
		document.getElementById(this.error_div_id).style.display = 'none';
		}
	}
cState.prototype.refreshHistory = function( title ) {
	if($.browser.msie) {
		var iframe = $("#jQuery_history")[0].contentDocument || $("#jQuery_history")[0].contentWindow.document; //changed 13:12 09.10.2008
		if ( title == '' ) {
			title = iframe.title;
			}
		iframe.open();
		iframe.close();
		iframe.location.hash = this._curHash;
		iframe.title = title;
		}
	}
cState.prototype.refreshAnchor = function(  ) {
	location.hash = '#'+'catalog:'+'type='+this.obj_type+'&id='+this.obj_id+this.dop_params.getGET( );
	}
cState.prototype.getAnchor = function(  ) {
	return '#'+'catalog:'+'type='+this.obj_type+'&id='+this.obj_id+this.dop_params.getGET( );
	}
cState.prototype.alertMyself = function( ) {
	alert('type='+this.obj_type+' id='+this.obj_id+this.dop_params.myToString());
	}
cState.prototype.changeTo = function( obj_type, obj_id, dop_params, href_value ) {
	if ( typeof(obj_type) == 'string' && obj_type != '' && typeof(obj_id) == 'number' && obj_id >= 0 && this.timeout_id == null) {
		if( $.browser.msie && parseInt( $.browser.version ) >= 8 ) { //IE 8.0 hack
			//return false;
			}
		//получаем дополнительне параметры в виде GET-параметров
		var tmp_dop_params;
		if (this.obj_type == obj_type && this.obj_id == obj_id) {
			tmp_dop_params = new dopParams( this.dop_params );
			tmp_dop_params.change( dop_params );
			if (typeof(dop_params.gia) == 'undefined') {
				tmp_dop_params.gia = -1;
				}
			}
		else {
			tmp_dop_params = new dopParams( dop_params );
			}
		var get_dop_params = tmp_dop_params.getGET( );
		delete tmp_dop_params;
		
		//создаем timeout
		this.timeout_id = window.setTimeout('c_failedAjax_handler(\''+href_value+'\')', this.timeout_value);
		
		//делаем асинхронный запрос
		var tmp_hidden_div = document.getElementById( "c_hidden_div" );
		if( tmp_hidden_div ) {
			$( tmp_hidden_div ).load(adress_pr+"klarnetCMSlocal/catalog/c_get_content.php?new_type="+obj_type+"&new_id="+obj_id+"&old_type="+this.obj_type+"&old_id="+this.obj_id+get_dop_params);
			/*
			this.obj_type = obj_type;
			this.obj_id = obj_id;
			this.refreshAnchor();
			this._curHash = this.getAnchor();
			window.clearTimeout( this.timeout_id );
			this.timeout_id = null;
			var new_anchor = this.getAnchor();
			if ($.browser.msie) {
				var ihistory = $("#jQuery_history")[0]; // TODO: need contentDocument?
				var iframe = ihistory.contentWindow.document;
				iframe.open();
				iframe.close();
				iframe.location.hash = new_anchor;
				}
				*/
			}
		document.body.style.cursor = "wait";
		$.cssRule("a", "cursor:wait");
		return true;
	} else {
		return false;
		}
	}

var curState = new cState;


//обработчик изменения select'ов "быстрого перехода"
function c_select_changed( obj_changed ) {
	var selected_direction 	= document.getElementById( 'c_select_directions' );
	var selected_brand 		= document.getElementById( 'c_select_brands' );
	var selected_product	= document.getElementById( 'c_select_products' );

	if ( parseInt(selected_product.value) == selected_product.value && parseInt(selected_product.value) != 0 && obj_changed == 'product' ) {
		curState.changeTo('product', parseInt(selected_product.value), {} , '');
		}
	else if ( parseInt(selected_brand.value) == selected_brand.value && parseInt(selected_brand.value) != 0 && obj_changed != 'direction' ) {
		curState.changeTo('brand', parseInt(selected_brand.value), {} , '');
		}
	else if ( parseInt(selected_direction.value) == selected_direction.value && parseInt(selected_direction.value) != 0 ) {
		curState.changeTo('direction', parseInt(selected_direction.value), {} , '');
		}
	}