function processError(transport){
    var status = transport.responseText[0];
    if (status == "!"){ //error mark
	var error_msg=transport.responseText.substr(1);
	alert(error_msg);
	return true;
    }
    return false;
}
function getBodySwf(){
    var swf=null;
    swf=window['id_shoppers'] || document['id_shoppers'];
    return swf;
};


function toggle_block(name){
    var header=$('header_'+name);
    var block=$('block_'+name);
    block.style.display=(block.style.display==''?'none':'');
    if(block.style.display == '') { //visible
	header.select("li.edit a")[0].innerHTML = 'свернуть';
	header.select("li.edit a img")[0].src=_MEDIA_URL+"i/ic_bullet_close.gif";
    }else{
	header.select("li.edit a")[0].innerHTML = 'развернуть';
	header.select("li.edit a img")[0].src=_MEDIA_URL+"i/inner/icon_collapsed.png";
    }
}

function _do_view(name){
    try{
	$$('#header_'+name+' .view_hdl')[0].style.display='none';
	$$('#header_'+name+' .edit_hdl')[0].style.display='block';
    }catch(e){
    }
}
function view(name){
    if (window.confirm("Вы хотите сохранить сделанные изменения?")){
	save_form(name);
    }else{
	cancel_form(name);
    }
    _do_view(name);
}
function edit(name){
    var rand=Math.round(Math.random()*100000);
    var url = '/'+$UID+'/profile/edit/'+escape(name)+'/?sid='+SESSION_ID+'&rand='+rand;
    var contactRequest= new Ajax.Request(
        url, {
            method: 'GET',
            asynchronous:true,
            onSuccess:function(transport){
		if(processError(transport)) return;
		$('block_'+name).style.display='';
		$('block_'+name).update(transport.responseText);
		$$('#header_'+name+' .view_hdl')[0].style.display='block';
		$$('#header_'+name+' .edit_hdl')[0].style.display='none';
            },
            onFailure: function(transport){
		w=window.open("");
		w.document.write(transport.responseText);
		_do_view(name);
            }
        }
    );
}


function save_form(name){
    $$('.form_chunk').each(function(e){
	var a = e.id.split('_');
	_save_form(a[3]);
    });
}
function _save_form(name){
    var rand=Math.round(Math.random()*100000);
    var form = $('__form_'+name);
    if(!form)
	return;
    var data = form.serialize();
    var url = form.action + '&rand='+rand;
    new Ajax.Request(
        url, {
            method: 'post',
            parameters:data,
            asynchronous:true,
            onSuccess:function(transport){
		if(processError(transport)) return;
		$('block_'+name).update(transport.responseText);
		// alert('Form data saved!') 
            },
            onFailure: function(transport){
		w=window.open("");
		w.document.write(transport.responseText);
            }
        }
    );
    // console.log(form);
}
function cancel_form(name){
    var form = $('__form_'+name);
    if(!form)
	return;
    var url = form.action;
    
    new Ajax.Request(
        url, {
            method: 'post',
            parameters:{
		'__cancel__':true
	    },
            asynchronous:true,
            onSuccess:function(transport){
		$('block_'+name).update(transport.responseText);
		_do_view(name);
		// alert('Form data saved!') 
            },
            onFailure: function(transport){
		w=window.open("");
		w.document.write(transport.responseText);
            }
        }
    );
    // console.log(form);
}

function _add_option(element, selected,value, custom_value){
    var el = document.createElement('option');
    el.value = (custom_value==null)?value:custom_value;
    if (el.value == selected){
	el.selected=true;
    }
    el.text = value;
    try{
	element.add(el,null);
    }catch(e){
	element.add(el);
    }
}
function country_changed(){
    var country = $('id_country');
    var city_list = $('id_citylist');
    var city = $('id_city');
    new Ajax.Request(
        '/ajax/tools/cities/', {
            method: 'post',
            parameters:{
		'id':country.value
	    },
            asynchronous:true,
            onSuccess:function(transport){
		var countries = transport.responseText.trim();
		if(countries.length){
		    countries = countries.split('\n');
		}else{
		    countries =[];
		}
		for (var i = city_list.length - 1; i>=0; i--) {
		    city_list.remove(i);
		}
		for (var i =0; i < countries.length; i++){
		    _add_option(city_list, city.value,countries[i]);
		}

		_add_option(city_list,city.value,'Другой...','');
		$('id_city').value = countries[0];

		city_changed();
            },
            onFailure: function(transport){
		w=window.open("");
		w.document.write(transport.responseText);
            }
        }
    );
}
function city_changed(){
    var val = $('id_citylist').value;
    var fset = $('id_fieldset_city');
    $('id_city').value = val;
    if (val == ''){
	fset.show()
    }else{
	fset.hide()
    }
}



function friend(id, status/*:boolean*/){
    if(!SESSION_ID){
	window.location.href='/login/';
    }
    var url='/ajax/friend/?sid='+SESSION_ID;
    new Ajax.Request(
        url,{
            method: 'post',
            parameters:{'id':id, 'status':(status?"1":"0")},
            onSuccess: function(transport){
                var text=transport.responseText;
                if(text=='OK'){
		    $('id_add_to_friends').removeClassName('friend');
		    $('id_add_to_friends').removeClassName('notfriend');
		    $('id_add_to_friends').addClassName(status?'friend':'notfriend');
		}
	    },
            onFailure: function(transport){
                //a lert(transport.responseText)
            }
	    
        }
    )
}


function move_control(e){
    try{
	e=Event.extend(e)
	var i = $('id_photo_control');
	i.style.position="absolute";
	i.style.width="50px";
	i.style.size=1;

	i.style.opacity='0';

	var left = (document.documentElement.scrollLeft || document.body.scrollLeft) + e.clientX;
	if(Prototype.Browser.IE){
	    // alert('q');
	    i.style.left=(left-15)+'px';
	    // i.style.width='1px';
	    i.style.filter = 'alpha(opacity=0)'
	}else if(
	    (navigator.userAgent.toLowerCase().indexOf('chrome') > -1)
	    ||
	    (navigator.userAgent.toLowerCase().indexOf('iron/') > -1)
	){
	    i.style.left=(left-15)+'px';
	    i.style.width='100px';
	    // i.style.opacity='50';
	}else if(Prototype.Browser.Opera){
	    i.style.left=(left-55)+'px';
	    i.style.width='100px';
	    // alert('q');
	}else{
	    i.style.left=(left-110)+'px';
	    i.style.width='100px';
	    // alert(navigator.userAgent);
	}

	i.style.top=(e.clientY+(document.documentElement.scrollTop || document.body.scrollTop)-5)+'px';
	
	i.style.zIndex=1200;
	i.style.color='#ffffff';
	i.style.backgroundColor='#ffffff';
	// i.style.visibility='hidden';
	// i.style.cursor='hand';
	i.style.cursor='pointer';
    }catch(e){
	console.log(e);
    }
}


function open_upload_window(e){
    // alert("open upload window");
    var url = '/'+$UID+'/profile/uploadphoto/?sid='+SESSION_ID;
    window.open(url, 'upload','status=0, toolbar=0, location=0, menubar=0, resizable=1, width='+300+',height='+100)
}

function _processUpload(s){
    if(s.substr(0,3) == 'OK:'){
	img_src = s.substr(3)
	$('id_my_image').src=img_src;
	$('account_thumb').src=img_src.replace("/profile/","/thumb/");
	// alert(img_src);
    }else{
	console.log(s);
    }
}


function pers_ffunc_init( ){
    try {
	var skin=parseInt(pers_params.skin,16);
	var eyes=parseInt(pers_params.eyes,16);
	var START_PARAMS = {
	    sex:pers_params.sex,
	    skin_color:skin,
	    eyes_color:eyes,
	    cheeks_color:skin,
	    lips_color:skin,
	    shadows_color:skin,
	    emotion_id:1,
	    body_type:1,
	    USER_GEAR:[]//_getGearList4Flash()
	};
	return START_PARAMS;
    } catch (e){return false;}
}

function _getGearList4Flash(){
    var s = Base64.decode(pers_params.gear)
    var a = s.split("\n");
    var gear = {}
    for ( var j = 0; j< a.length; j++){
	var item = a[j];
	if (!item.length){
	    continue;
	}
	var b = item.split(":",6);
	var pos = b[3].split(',');
	var colors = b[4].split(',');

	gear[b[0]]={
	    id:b[0],
	    layer_id:parseInt(b[2],10),
	    b_total:50,//parseInt(b[1],10),
	    item_color1: parseInt(colors[0]),
	    item_color2: parseInt(colors[1]),
	    item_color3: parseInt(colors[2]),
	    x: parseInt(pos[0]),
	    y: parseInt(pos[1]),
	    text_label: b[5]
	};
    }
    return gear;
}
var lastGearHash = '';
function embedCharacter(url){
    var fv='';
    var params = {allowScriptAccess: "always",bgcolor:'#FFFFFF',flashVars:'gearpfx='+_MEDIA_URL+'gear/'} ;
    // console.log(params);
    var atts = { id: 'id_shoppers'};

    swfobject.embedSWF(
	url,
        'id_shoppers',
        '223',
        '330',
        "9.0.0",
        null,
        null,
        params,
        atts
    );

    var update = function(){
        var url= getUpdateUrl("gear");
	    
	var params={
	    id:pers_params.id
	};
	var swf = getBodySwf();
	if(swf)
        new Ajax.Request(
            url, {
                method: 'post',
		parameters:params,
                onSuccess: function(transport){
		    if (processError(transport)) return;
		    var root=transport.responseXML.getElementsByTagName('user').item(0);
		    var emo = parseInt(root.getAttribute('emotion'),10);


		    var eyes_color  = parseInt(root.getAttribute('eyes'),16);
		    var skin_color  = parseInt(root.getAttribute('skin'),16);

		    var newList = [];
		    var items=root.getElementsByTagName('item');
		    for (var i = 0; i < items.length; i++) {
			var item= items.item(i);
			var code=item.getAttribute('id');
			var id=parseInt(code.substr(0,5),10);
			var el = {
			    id:id,
			    code:code,
			    colors:item.getAttribute('colors').split(','),
			    label:item.getAttribute('label'),
			    layer:item.getAttribute('layer'),
			    x:item.getAttribute('x'),
			    y:item.getAttribute('y')
						};
 			for(var j = 0 ; j < el.colors.length; j++){
 			    el.colors[j]=parseInt(el.colors[j],10)
 			}
			newList.push(el);
		    };
 	            var gear ={}
		    for(var i = 0; i < newList.length; i++){
			var item=newList[i];
			gear[item.code]={
			    id:item.code,
			    layer_id:item.layer,
			    b_total:50,
			    x:item.x,
			    y:item.y,
			    item_color1:item.colors[0], 
			    item_color2:item.colors[1],
			    item_color3:item.colors[2],
			    text_label:item.label
			};
		    }
		    var s = Base64.encode(Object.toJSON(gear));

		    if(s != lastGearHash){
			lastGearHash = s;
			swf.jsev_newGear(gear);
		    }
		    
 		    swf.jsev_personageUserChangedEmotion(emo);
                },
                onFailure:function(transport){
                    alert._error("error updating own gear");
                }
            }
        );
	window.setTimeout(update,5000);
    }
    window.setTimeout(update,1000);

}



/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/

var Base64 = {
    
    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
    
    // public method for encoding
    encode : function (input) {
	var output = "";
	var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
	var i = 0;
	
	input = Base64._utf8_encode(input);
	
	while (i < input.length) {
	    
	    chr1 = input.charCodeAt(i++);
	    chr2 = input.charCodeAt(i++);
	    chr3 = input.charCodeAt(i++);
	    
	    enc1 = chr1 >> 2;
	    enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
	    enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
	    enc4 = chr3 & 63;
	    
	    if (isNaN(chr2)) {
		enc3 = enc4 = 64;
	    } else if (isNaN(chr3)) {
		enc4 = 64;
	    }
	    
	    output = output +
		this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
		this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
	    
	}
	
	return output;
    },
    
    // public method for decoding
    decode : function (input) {
	var output = "";
	var chr1, chr2, chr3;
	var enc1, enc2, enc3, enc4;
	var i = 0;
	
	input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
	
	while (i < input.length) {
	    
	    enc1 = this._keyStr.indexOf(input.charAt(i++));
	    enc2 = this._keyStr.indexOf(input.charAt(i++));
	    enc3 = this._keyStr.indexOf(input.charAt(i++));
	    enc4 = this._keyStr.indexOf(input.charAt(i++));
	    
	    chr1 = (enc1 << 2) | (enc2 >> 4);
	    chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
	    chr3 = ((enc3 & 3) << 6) | enc4;
	    
	    output = output + String.fromCharCode(chr1);
	    
	    if (enc3 != 64) {
		output = output + String.fromCharCode(chr2);
	    }
	    if (enc4 != 64) {
		output = output + String.fromCharCode(chr3);
	    }
	    
	}
	
	output = Base64._utf8_decode(output);
	
	return output;
	
    },
    
    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
	string = string.replace(/\r\n/g,"\n");
	var utftext = "";
	
	for (var n = 0; n < string.length; n++) {
	    
	    var c = string.charCodeAt(n);
	    
	    if (c < 128) {
		utftext += String.fromCharCode(c);
	    }
	    else if((c > 127) && (c < 2048)) {
		utftext += String.fromCharCode((c >> 6) | 192);
		utftext += String.fromCharCode((c & 63) | 128);
	    }
	    else {
		utftext += String.fromCharCode((c >> 12) | 224);
		utftext += String.fromCharCode(((c >> 6) & 63) | 128);
		utftext += String.fromCharCode((c & 63) | 128);
	    }
	    
	}
	
	return utftext;
    },
    
    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
	var string = "";
	var i = 0;
	var c = c1 = c2 = 0;
	
	while ( i < utftext.length ) {
	    
	    c = utftext.charCodeAt(i);
	    
	    if (c < 128) {
		string += String.fromCharCode(c);
		i++;
	    }
	    else if((c > 191) && (c < 224)) {
		c2 = utftext.charCodeAt(i+1);
		string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
		i += 2;
	    }
	    else {
		c2 = utftext.charCodeAt(i+1);
		c3 = utftext.charCodeAt(i+2);
		string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
		i += 3;
	    }
	    
	}
	
	return string;
    }
    
}
