var clientPC = navigator.userAgent.toLowerCase();
var clientVer = parseInt(navigator.appVersion);
var is_ie = ((clientPC.indexOf("msie") != -1) && (clientPC.indexOf("opera") == -1));
var is_win = ((clientPC.indexOf("win")!=-1) || (clientPC.indexOf("16bit") != -1));
var set_on = false;

function countHash(hash){
	var counter = 0;
    for( var k in hash )
        counter++
    return counter

}

function SendSupport()
{
	var message = $("div#dialog div#content_dialog div.support textarea").val();
	var title = $("div#dialog div#content_dialog div.support input.title").val();
	var title_type = $("div#dialog div#content_dialog div.support select#type").val();
	if (title_type != 1)
	{
		title = $("div#dialog div#content_dialog div.support select#type option:selected").text();
	}
	
	var data =
	{
		"message" 	 : message,
		"title"	  	 : title,
		"title_type" : title_type
	};
	getAjax({c: 'Character', m: 'SendSupport', 'data': data});
}

function SupportTitleChange(value)
{
	if (value != 1)
	{
		$("div#dialog div#content_dialog div.support .title").hide();
	}
	else
	{
		$("div#dialog div#content_dialog div.support .title").show();
	}
}

// Фнкция обработки времени
function formatDateNull(str){
	if(str < 10){
		return "0"+str;
	}else{
		return str;
	}

}

function formatIntToTime(str){
	var theDate = new Date(str * 1000);
	var d = formatDateNull(theDate.getDate());
	var m = formatDateNull(theDate.getMonth() + 1 );
	var y = formatDateNull(theDate.getFullYear());
	var h = formatDateNull(theDate.getHours());
	var i = formatDateNull(theDate.getMinutes());

	var ret = d +"."+ m +"."+ y +" "+ h +":"+ i;
	return ret;
}

function setCookie (name, value, expires, path, domain, secure) {
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

function getCookie(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}

function openDialog(param){
	if(param){
		$("#title_dialog").html(param['title']);
		$("#content_dialog").html(param['cont']);
	}
	
	
	$("#dialog").show();
	
	//if (user_id == 210271)
	{
		//alert($("#dialog").length);
	}
	//$("#blockFrame").show();
}


function print_r( array, return_val ) {    // Prints human-readable information about a variable

    var output = "", pad_char = " ", pad_val = 4;
 
    var formatArray = function (obj, cur_depth, pad_val, pad_char) {
        if(cur_depth > 0)
            cur_depth++;
 
        var base_pad = repeat_char(pad_val*cur_depth, pad_char);
        var thick_pad = repeat_char(pad_val*(cur_depth+1), pad_char);
        var str = "";
 
        if(obj instanceof Array || obj instanceof Object) {
            str += "Array\n" + base_pad + "(\n";
            for(var key in obj) {
                if(obj[key] instanceof Array || obj[key] instanceof Object) {
                    str += thick_pad + "["+key+"] => "+formatArray(obj[key], cur_depth+1, pad_val, pad_char);
                } else {
                    str += thick_pad + "["+key+"] => " + obj[key] + "\n";
                }
            }
            str += base_pad + ")\n";
        } else {
            str = obj.toString();
        };
 
        return str;
    };
 
    var repeat_char = function (len, chr) {
        var str = "";
        for(var i=0; i < len; i++) { str += chr; };
        return str;
    };
 
    output = formatArray(array, 0, pad_val, pad_char);
 
    if(return_val !== true) {
        return output;
        //document.write("<pre>" + output + "</pre>");
        //return true;
    } else {
        return output;
    }
}

function closeDialog(){	
	$("#dialog").hide();
	//$("#blockFrame").hide();
	$("#title_dialog").html();
	$("#content_dialog").html();
}

function ajaxRequest(backend,hash,onRredyFunction){
	var req = new JsHttpRequest();
	    req.onreadystatechange = function() {
	        if (req.readyState == 4) {
	        	ajaxBackend(req.responseJS,req.responseText);
	        	if(onRredyFunction!=undefined){
	        		eval(onRredyFunction);
	        	}
	        }
	    }
	    req.open(null, '/'+backend, false);
	    req.send(hash);
}




function getAjax(hash){
	if(!hash){
		var hash = {};
	}
	if(!hash.ajax)
	{
		hash.ajax = 1;
	}
	params = $.param(hash);
	//$.getJSON('/index.php?'+params, {}, function(json){
	$.post('/index.php', hash, function(json){	
		$("#debug").html((json.error));
		$("#debug").append((json));
		if(json.result){
			for(key in json.result){
				var tmp = json.result[key];			
				if(tmp["redirect"]){
					top.location=tmp["redirect"];
				}		
				if(tmp["act"]==0){
					$("#"+tmp["div"]).html(tmp["cont"]);
				}else if(tmp["act"]==1){
					$("#"+tmp["div"]).append(tmp["cont"]);
				}else if(tmp["act"]==2){
					$("#"+tmp["div"]).prepend(tmp["cont"]);
				}else if(tmp["act"]==3){
					$("#"+tmp["div"]).html("");
				}			
				if(tmp["style"]){
					for(var k in tmp["style"]){
						$("#"+tmp["div"]).css([k],tmp["style"][k]);
					}
				}
				if(tmp["js"]){
					eval(tmp["js"]);
				}
						
			}
		}
		if(json.debug){
			// Обработка вывода для JSON.debug
		}
	}, "json");
}

function var_dump(obj) {
   if(typeof obj == "object") {
      return "Type: "+typeof(obj)+((obj.constructor) ? "\nConstructor: "+obj.constructor : "")+"\nValue: " + obj;
   } else {
      return "Type: "+typeof(obj)+"\nValue: "+obj;
   }
}

function ajaxBackend(result,error){	
	alert(var_dump(result));



	if(error){
		if($('#dialog')){
			$("#content_dialog").html(error);
			openDialog();
		}
	}
	if(result){
		for(key in result){
			var tmp = result[key];			
			if(tmp["redirect"]){
				//alert(tmp["redirect"]);
				top.location=tmp["redirect"];
			}		
			if(tmp["act"]==0){
				$("#"+tmp["div"]).html(tmp["cont"]);
			}else if(tmp["act"]==1){
				$("#"+tmp["div"]).append(tmp["cont"]);
			}else if(tmp["act"]==2){
				$("#"+tmp["div"]).prepend(tmp["cont"]);
			}else if(tmp["act"]==3){
				$("#"+tmp["div"]).html("");
			}			
			if(tmp["style"]){
				for(var k in tmp["style"]){
					//alert(k+'=>'+tmp["style"][k]);
					ge(tmp["div"]).style[k]=tmp["style"][k];
				}
			}
			if(tmp["js"]){
				eval(tmp["js"]);
			}
					
		}
	}
}



function GetInfo(personage_id, name){
	//ajaxRequest("index.php",{'c':'info','user_id':personage_id,'ajax':'1'},"openDivInfo()");
	var req = (personage_id != null) ? "?id="+personage_id : "?name="+name;
	$("#content_PersonageInfo").html("<iframe noresize='noresize' scrolling='no' frameborder='no' width='710' height='590' style='border:0px;' src='/Character/info/"+req+"'></iframe>");
	openDivInfo();
}


function openDivInfo(){
	$("#PersonageInfo").show();
}
function closeDivInfo(){
	$("#PersonageInfo").hide();
}
