/**
* Default types and definitions should be loaded with each page as default
**/

/** This function will load all forms, input's vars and etc... **/
function customInc(){
	/** Check if language select block is present and build objects **/
	var lang_select = document.getElementById("lang_select");
	if(lang_select && typeof setLangSelect == 'function')
		setLangSelect();
	/** Check if registration form is present and do initializations for it **/
	var reg_form = document.getElementById("reg_form");
	if(reg_form && typeof setRegistrationBlock == 'function')
		setRegistrationBlock();
	/** Check if have menu object and set active links **/
	var menu_default = document.getElementById("menu_default");
	if(menu_default && typeof setMenuActiveLink == 'function')
		setMenuActiveLink(menu_default);
	/** Check if have simple search block present **/
	var search_simple = document.getElementById("srch_smpl");
	if(search_simple && typeof setSearchSimple == 'function')
		setSearchSimple();
	/** Check if users list block is present and fill info **/
	var users_list = document.getElementById("users_list");
	if(users_list && typeof setSpanCustValues == 'function')
		setSpanCustValues(users_list);
	/** Check if navigate block panel exists and fill appropriate vars **/
	var navigate_data = document.getElementById("navigate_data");
	if(navigate_data && typeof setNavigateDataBlock == 'function')
		setNavigateDataBlock(navigate_data);
	/** Check if we have a login block present **/
	var login_block = document.getElementById("login_block");
	if(login_block && typeof setLoginBlock == 'function')
		setLoginBlock();
	/** Check if we have a login forgot block present (called from login block) **/
	var login_forgot = document.getElementById("login_forgot");
	if(login_forgot && typeof setLoginForgot == 'function')
		setLoginForgot();
	/** Check if conversation block present and send message two (may be even the message itself) **/
	var conv_block = document.getElementById("conv_block");
	var conv_block_text = document.getElementById("conv_block_text");
	var conv_send = document.getElementById("conv_send");
	if(conv_send && conv_block && typeof setConversationBlock == 'function')
		setConversationBlock(conv_send);
	/** Check if user images block is exists **/
	var user_images = document.getElementById("user_images");
	if(user_images && typeof setUserImagesBlock == 'function')
		setUserImagesBlock();
	/** Show hide alert message block if such present if not then alert block should be neither **/
	var alert_block_close = document.getElementById("alert_block_close");
	if(alert_block_close && typeof alertBlock == 'function')
		addEvent(alert_block_close,'click',alertBlock);
		
	/** Edit users profile external popup block **/
	var profile_edit = document.getElementById("profile_edit");
	if(profile_edit && profile_edit.getAttribute("data-cust") && typeof popupWinObj == 'function')
		popupWinObj(profile_edit,profile_edit.getAttribute("data-cust"),1000,700);
	
	/** Change profile password **/
	var profile_chg_pass = document.getElementById("profile_chg_pass");
	var profile_chg_pass_show = document.getElementById("profile_chg_pass_show");
	if(profile_chg_pass && profile_chg_pass_show && typeof setChangePassword == 'function')
		setChangePassword();
	
	/** Profile password forgot **/
	var profile_new_pass = document.getElementById("profile_new_pass");
	if(profile_new_pass && typeof setPasswordForgot == 'function')
		setPasswordForgot();
	/** Profile images show upload and edit (used in users profile) **/
	var profile_images = document.getElementById("profile_images");
	var profile_images_upload = document.getElementById("profile_images_upload");
	if(profile_images && profile_images_upload && typeof profileImages.init() == 'function')
		profileImages.init();
	/** Profile edit and update (used in users profile) **/
	var profile_update = document.getElementById("profile_update");
	var profile_update_title = document.getElementById("profile_update_title");
	if(profile_update && profile_update_title && typeof profileEdit.init() == 'function')
		profileEdit.init();
};

/**
* Set language selecting parameters and methods
*/
function setLangSelect(){
	var lang_select = document.getElementById("lang_select");
	/** Create IMG element and append it to body **/
	var elm_img = document.createElement("img");
	elm_img.setAttribute("id","lang_select_call");
	elm_img.setAttribute("lang",getUrl['lang']);
	/** All templates share one common lib **/
	elm_img.setAttribute("src",getUrl.origin+'/templates/all/lang-'+getUrl['lang']+'.png');
	addEvent(elm_img,'click', function(evn){
		alertBlock(true,'lang_select');
	});
	var langs=lang_select.getElementsByTagName("img");
	for(var lang in langs){
		if(typeof(langs[lang]) === 'object')
			if(langs[lang].lang != getUrl.lang){
				addEvent(langs[lang],'click',function(scope){
					elem = getEventTarget(scope);
					var cur_path = getUrl.path.replace('/'+getUrl.lang,"");
					window.location.replace(getUrl.origin+'/'+elem.lang+cur_path+getUrl.search);
				});
			}
	}
	document.body.appendChild(elm_img);
}

/**
* Set registration block parameters and methods
*/
function setRegistrationBlock(){
	/** get today's day but this is good for the time the page was loaded.... **/
	var date_today = new Date();
	var reg_title = document.getElementById("reg_title");
	var reg_gender = document.getElementById("reg_gender");
	var reg_birth_dd = document.getElementById("reg_birth_dd");
	var reg_birth_yy = document.getElementById("reg_birth_yy");
	var reg_birth_mm = document.getElementById("reg_birth_mm");
	var reg_email = document.getElementById("reg_email");
	var reg_user_name = document.getElementById("reg_user_name");
	var reg_password = document.getElementById("reg_password");
	var reg_password_rep = document.getElementById("reg_password_rep");
	var reg_captcha = document.getElementById("reg_captcha");
	var reg_captcha_reload = document.getElementById("reg_captcha_reload");
	var reg_captcha_img = document.getElementById("reg_captcha_img");
	var reg_submit = document.getElementById("reg_submit");
	/** populate dates fields **/
	fillNumericOption(reg_birth_dd,1,31);
	fillNumericOption(reg_birth_mm,1,12);
	fillNumericOption(reg_birth_yy,date_today.getUTCFullYear()-18,date_today.getUTCFullYear()-99);
	/** set minimal of 18 years old from today **/
	reg_birth_dd.value = date_today.getUTCDate();
	reg_birth_mm.value = date_today.getUTCMonth()+1;
	reg_birth_yy.value = date_today.getUTCFullYear()-18;
	/** event on load we recall the captcha **/
	reg_captcha_img.src = getUrl.origin+'/helpers/showCaptcha.php?SID=' + Math.random() + new Date().getTime();
	/** basic check that all data is correct before submitting it to server **/
	addEvent(reg_submit,'click', function(scope){
		cancelElementEvent(scope);
		// disable button while submitting or checking
		reg_submit.disable = true;
		// simple flag for proceed procedure
		var is_proceed = true;
		if(reg_captcha.value.length < 3){
			is_proceed = false;
			reg_title.innerHTML = langObj('CAPTCHA_WRONG');
		}
		if(reg_password.value != reg_password_rep.value){
			is_proceed = false;
			reg_title.innerHTML = langObj('PASSWORD_NOT_MATCH');
		}
		if(reg_password.value.length < 4){
			is_proceed = false;
			reg_title.innerHTML = langObj('PASSWORD_WRONG');
		}
		// check if email value present and correct
		if(!isLikeEmail(reg_email)){
			is_proceed = false;
			reg_title.innerHTML = langObj('EMAIL_WRONG');
		}
		// check if user set birthday
		if(!reg_date_chk()){
			is_proceed = false;
			reg_title.innerHTML = langObj('DATE_WRONG');
		}
		// check if user set his gender
		if(!(reg_gender.value == "1" || reg_gender.value == "2")){
			is_proceed = false;
			reg_title.innerHTML = langObj('GENDER_WRONG');
		}
		// check if user set his user name
		if(reg_user_name.value.length > 40 && reg_user_name.value.length < 4){
			is_proceed = false;
			reg_title.innerHTML = langObj('NAME_WRONG');
		}
		// if ok post else alert something wrong...
		if(is_proceed){
			var callback = function(reg_result){
					if(reg_result == '')
						reg_title.innerHTML = langObj('ERROR_RETRY');
					else{
						if(reg_result == 'SUCCESS')
							alertBlock(true,'alert_msg',langObj('ACCOUNT_REGISTERED'),320);
							/** because i'm using title the result is predefined **/
						reg_title.innerHTML = langObj(reg_result);
					}
				};
				postData('/login/register/action',{user_gender:reg_gender.value,
													user_birth:reg_birth_yy.value + "-" + reg_birth_mm.value + "-" + reg_birth_dd.value,
													user_email:reg_email.value,
													user_name:reg_user_name.value,
													user_password:reg_password.value,
													user_password_rep:reg_password_rep.value,
													user_captcha:reg_captcha.value
													}, callback);
		}
		reg_title.style.color = "#F00";
		reg_submit.disabled = false;
	});
	/** date checking for minimal birth and correct existing date **/
	function reg_date_chk(){
		var date = new Date(Date.UTC(reg_birth_yy.value,reg_birth_mm.value-1,reg_birth_dd.value));
		var convertedDate = "" + date.getUTCFullYear() + (date.getUTCMonth()+1) + date.getUTCDate();
		var givenDate = "" + reg_birth_yy.value + reg_birth_mm.value + reg_birth_dd.value;
		if(givenDate != convertedDate)
			return false;
		if(reg_birth_yy.value == date_today.getUTCFullYear()-18){
			/** else check if month is greater or equal today's **/
			if(reg_birth_mm.value > date_today.getUTCMonth()+1){
				return false;
			}else if(reg_birth_mm.value == date_today.getUTCMonth()+1){
				/** else check if day is greater than today's **/
				if(reg_birth_dd.value >= date_today.getUTCDate()+1)
					return false;
			}
		}
		/** default returning true correct date and age **/
		return true;
	};
	/** reload the captcha **/
	addEvent(reg_captcha_reload,'click', function(scope){
		cancelEventBubble(scope);
		cancelEventDefault(scope);
		reg_captcha_img.src = '';
		reg_captcha_img.src = getUrl.origin+'/helpers/showCaptcha.php?SID=' + Math.random() + new Date().getTime();
	});
};

/**
* Full window container block call gets 
* @show : bool - hide/show, @show_item : the block id, @show_HTML : optional inner HTML, @show_width : optional width in PX may be defined
*/
function alertBlock(show,show_item,show_HTML,show_width){
	var alert_block = document.getElementById("alert_block");
	/** get alert block children if such exists ...**/
	var alert_children = alert_block.children[0].children;
	/** basic need for changing this without using the styles **/
	var alert_children_total = alert_children.length;
	while(alert_children_total){
		alert_children_total--;
		alert_children[alert_children_total].style.display = "none";
	}
	if(show && alert_children[show_item]){
		alert_block_close.style.display = "block";
		if(show_HTML)
			alert_children[show_item].innerHTML = show_HTML;
		if(show_width)
			alert_children[show_item].style.width = show_width + "px";
		alert_children[show_item].style.display = "block";
		alert_block.style.display = "block";
	}else{
		alert_block.style.display = "none";
	}
};

/**
* Prepare user images block to show the images 
*/
function setUserImagesBlock(){
	var images_show = document.getElementById("user_images_show");
	var images_avatar = document.getElementById("user_images_avatar");
	var img_list = user_images.getAttribute("data-cust");
	var img_sel = user_images.getAttribute("data-sel");
	if(img_list != ""){
		img_list = img_list.split("|");
		for(key = 1; key < img_list.length; key++){
			if(img_list[key] !== undefined){
				var elm_img = document.createElement("img");
				elm_img.setAttribute("src",getUrl.origin+'/'+img_list[key]);
				addEvent(elm_img,'click', function(evn){
					var elem ,evn = evn ? evn : evn.event; 
					elem = evn.srcElement ? evn.srcElement : evn.target;
					document.getElementById("user_images_avatar").src = elem.src;
				});
				images_show.appendChild(elm_img);
				/** If image is unreachable for some reason... remove it **/
				elm_img.onerror = function() {
					elm_img.parentNode.removeChild(elm_img);
				};
			}
		}
		/** Check if user selected any default image to display **/
		if(img_sel != ""){
			images_avatar.setAttribute("src",getUrl.origin+'/'+img_sel);
		/** if user not selected any default image to display and has any images set first as default **/
		}else if(img_list.length != 0){
			images_avatar.setAttribute("src",getUrl.origin+'/'+img_list[1]);
		/** user don't have any images to display **/
		}else{
		}
	}else{
		/* no need to show image selection panel */
		images_show.setAttribute("class","hidden");
	}
};

/**
* Prepare and get conversation (if such exists for current user)
*/
function setConversationBlock(conv_send){
	// should be inside on load function ?
	// Run timer/interval to check conversation status
	// setTimeout(updConvStat,2000);
	setInterval(function () {updConvStat("")}, 5000);
	conv_block_text.scrollTop = conv_block_text.scrollHeight;
	addEvent(conv_send,'click',function(scope){
		//e.preventDefault();
		var conv_msg = document.getElementById("conv_msg");
		if(conv_msg.value != ""){
			updConvStat(conv_msg.value);
			conv_block_text.scrollTop = conv_block_text.scrollHeight;
			/* clean box from send message */
			conv_msg.value = "";
		}
		cancelEventBubble(scope);
		cancelEventDefault(scope);
	});
};
/** Update conversation with new message
* THIS IS MY CUSTOM UPDATE
**/
function updConvStat(conv_msg){
	var params;
	/** call to clean the msg or and cancel undefined for "" an empty string **/
	conv_msg = cleanEmptyLF(conv_msg);
	/** if string empty simple message request from server **/
	if(conv_msg == "")
		params={user_con : 1 };
	else
		params={user_con : 1,user_msg: encodeURIComponent(conv_msg)};
	var convtion;
	/* here is self posting */
	postWithCallback(window.location.href,params,function(callback){
		convtion = callback;
	});
	/** deep check for error type or empty conversation **/
	if(convtion != undefined)
		if(convtion != "")
			updConv(conv_block_text,decodeURIComponent(convtion),conv_block.getAttribute("data-cust"));
};

/** Re-builds and updates conversation block from patterned string **/
function updConv(update_block,conversation,main_user){
	conversation = conversation.replace(/\n/g, '<br/>');
	var s,res = conversation.match(/<umsg>(.*?)<\/umsg>/gi);
	// remove any old text may be needed to scroll for long conversations
	update_block.innerHTML = '';
	var today = new Date();
	for(var key in res){
		// if(Object.prototype.hasOwnProperty.call(res, key)) {
		// if(key instanceof 'number'){
		// if(typeof key == 'number'){
		var ie_help = res[key].toString();
		s = ie_help.match(/<ucon>(.*?)<\/ucon>/gi);
		s[0] = (s[0].replace("<ucon>","").replace("</ucon>",""));
		s[1] = s[1].replace("<ucon>","").replace("</ucon>","");
		s[2] = s[2].replace("<ucon>","").replace("</ucon>","");
		s[3] = s[3].replace("<ucon>","").replace("</ucon>","");
		var elm_cht_box = document.createElement("div");
		elm_cht_box.setAttribute("class","inner-text");
		var elm_cht_cnt = document.createElement("span");
		var elm_cht_tim = document.createElement("span");
		if(s[0] == main_user){
			elm_cht_box.style.textAlign = "left";
			elm_cht_cnt.setAttribute("class","chat_left");
		}else{
			elm_cht_box.style.textAlign = "right";
			elm_cht_cnt.setAttribute("class","chat_right");
		}
		elm_cht_cnt.innerHTML = s[1];
		/** time chat for current date observation, full or half time display **/
		if(today.toDateString() == new Date(s[3]).toDateString()){
			elm_cht_tim.innerHTML = s[3].substring(11,16);
		}else
			elm_cht_tim.innerHTML = s[3].substring(0,16);
		elm_cht_box.appendChild(elm_cht_cnt);
		elm_cht_tim.setAttribute("class","chat_time");
		elm_cht_box.appendChild(elm_cht_tim);
		update_block.appendChild(elm_cht_box);
		update_block.scrollTop = update_block.scrollHeight;
		//}
	}
};
/** Cleans given string from any empty lines using LF CR removing and returning a new string with LF only, or empty one in case user hits just "ENTER" **/
function cleanEmptyLF(orig_str){
	if(!orig_str)
		return orig_str="";
	var lines = orig_str.split(/\r\n|\r|\n/g);
	var clean = 0;
	orig_str="";
	while(clean < lines.length){
		if(lines[clean].length>1){
			orig_str += lines[clean];
			/** Add new line only if it's not the last line **/
			if(clean < lines.length-1)
				orig_str += "\n";
		}
		clean++
	}
	return orig_str;
};
/** Timer events if such will needed**/
var getTiming = {allTime:"allTime"};
/** Setting timing for function call **/
function setTiming(func_name,func_min,run_once){
} 
/** POST action gets URL and callback parameters **/
function postWithCallback(url,values,callback){
	values = values || {};
	var http = new XMLHttpRequest();
	var params="";
	/** construct string with parameters from array (if such exists) **/
	for(var key in values){
		if(values.hasOwnProperty(key)){
			params += key + "=" + values[key] + "&";
		}
	}
	http.open("POST",url+'?'+params,false);
	http.onreadystatechange = function() {
		if(http.readyState == 4 && http.status == 200){
			/** return callback will not check for error statuses **/
			callback(http.responseText);
		}
	}
	/** Send the proper header information along with the request **/
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
	http.send(params);
};
/**
* Prepare login forgot password block for submitting
*/
function setLoginForgot(){
	var login_forgot_email = document.getElementById("login_forgot_email");
	var login_forgot_cap = document.getElementById("login_forgot_cap");
	var login_forgot_submit = document.getElementById("login_forgot_submit");
	var login_forgot_title = document.getElementById("login_forgot_title");
	var login_forgot_cap_reload = document.getElementById("login_forgot_cap_reload");
	var login_forgot_cap_img = document.getElementById("login_forgot_cap_img");
	login_forgot_cap_img.src = getUrl.origin+'/helpers/showCaptcha.php?SID=' + Math.random() + new Date().getTime();
	// check all data before submitting it to server
	addEvent(login_forgot_submit,'click', function(scope){
		cancelEventBubble(scope);
		cancelEventDefault(scope);
		var captcha_ok = false;
		var email_ok = false;
		/* check for minimal password length */
		if(login_forgot_cap.value.length > 3){
			captcha_ok = true;
		}
		/** simple email check for browsers not supporting validity **/
		email_ok = isLikeEmail(login_forgot_email);
		if(email_ok && captcha_ok){
			var callback = function(login_result){
				if(login_result == '')
					login_forgot_title.innerHTML = langObj('ERROR_RETRY');
				else{
					login_forgot_title.style.color = "#F00";
					login_forgot_title.innerHTML = langObj(login_result);
				}
			};
			postData('/login/forgotpassword',{user_email:login_forgot_email.value,'forgot_captcha':login_forgot_cap.value}, callback);
		}else{
			login_forgot_title.style.color = "#F00";
			login_forgot_title.innerHTML = langObj('INPUT_WRONG');
		}
	});
	addEvent(login_forgot_cap_reload,'click', function(scope){
		cancelEventBubble(scope);
		cancelEventDefault(scope);
		login_forgot_cap_img.src = '';
		login_forgot_cap_img.src = getUrl.origin+'/helpers/showCaptcha.php?SID=' + Math.random() + new Date().getTime();
	});
};


/**
* Prepare login form for submitting
*/
function setLoginBlock(){
	var login_email = document.getElementById("login_email");
	var login_password = document.getElementById("login_password");
	var login_rememberme = document.getElementById("login_rememberme");
	var login_submit = document.getElementById("login_submit");
	var login_block_title = document.getElementById("login_block_title");
	var login_password_reset = document.getElementById("login_password_reset");
	// check all data before submitting it to server
	addEvent(login_submit,'click', function(scope){
		cancelElementEvent(scope);
		var password_ok = false;
		var email_ok = false;
		/* check for minimal password length */
		if(login_password.value.length > 4){
			password_ok = true;
		}
	// 	if(login_email.validity){
	//		if(login_email.validity.valid)
	//			email_ok = true;
	//		else
	//			email_ok = false;
	//	}else{
			/* simple email check for browsers not supporting validity */
			email_ok = isLikeEmail(login_email); 
	//	}
		if(email_ok && password_ok){
			var params = {user_email:login_email.value,'user_password':login_password.value};
			if(login_rememberme.checked) params['user_rememberme'] = 1;
			var callback = function(login_result){
				if(login_result == 'SUCCESS')
					window.location.reload();
				else{
					login_block_title.style.color = "#F00";
					login_block_title.innerHTML = langObj(login_result);
				}
			};
			postData('/login/login',params, callback);
			// login_form.submit();
		}else{
			login_block_title.style.color = "#F00";
			login_block_title.innerHTML = langObj('LOGIN_FAILED');
		}
	});
	addEvent(login_password_reset,'click', function(scope){
		cancelElementEvent(scope);
		alertBlock(true,'login_forgot');
	});
};

/** Simple email check if it fits e-mail pattern, native and handmade for browser compatibility, returns boolean **/
function isLikeEmail(email_obj){
	if(email_obj.validity){// native...
		return email_obj.validity.valid;
	}else{// simple email check..
		var last_at_pos = email_obj.value.lastIndexOf('@');
		var last_dot_pos = email_obj.value.lastIndexOf('.');
		return (last_at_pos < last_dot_pos && last_at_pos > 0 && email_obj.value.indexOf('@@') == -1 && last_dot_pos > 2 && (email_obj.value.length - last_dot_pos) > 2 && (last_dot_pos - last_at_pos) > 2);
	}
};

/** Navigate panel block will fill appropriate vars **/
function setNavigateDataBlock(navigate_data){
	var navigate_request = getUrl.full.split('?')[1] ? "?"+getUrl.full.split('?')[1] : "?";
	var navigate_path = getUrl.path.substring(0,getUrl.path.lastIndexOf("/")+1);
	var navigate_range = document.getElementById("navigate_range");
	var navigate_data_total = parseInt(navigate_data.getAttribute("data-total"));
	var navigate_data_jump = parseInt(navigate_data.getAttribute("data-jump"));
	var navigate_data_pid = parseInt(navigate_data.getAttribute("data-pid"));
	var total_limit = Math.ceil(navigate_data_total / navigate_data_jump);
	var limiter = 1;
	if(navigate_data_pid == 0){
		limiter = 0;
		document.getElementById("navigate_first").setAttribute("class","navigate_block elm_dis");
		document.getElementById("navigate_previous").setAttribute("class","navigate_block elm_dis");
		// document.getElementById("navigate_first").style.backgroundColor = "beige";
		// document.getElementById("navigate_previous").style.backgroundColor = "beige";
	}else{
		document.getElementById("navigate_first").setAttribute("href",navigate_path + 0 + navigate_request);
		document.getElementById("navigate_previous").setAttribute("href",navigate_path + (navigate_data_pid - 1) + navigate_request);
	}
	if(navigate_data_pid == (total_limit - 1)){
		document.getElementById("navigate_next").setAttribute("class","navigate_block elm_dis");
		document.getElementById("navigate_last").setAttribute("class","navigate_block elm_dis");
		// document.getElementById("navigate_next").style.backgroundColor = "beige";
		// document.getElementById("navigate_last").style.backgroundColor = "beige";
		if(total_limit >= 3)
			limiter = 2;
	}else{
		document.getElementById("navigate_next").setAttribute("href",navigate_path + (navigate_data_pid + 1) + navigate_request);
		document.getElementById("navigate_last").setAttribute("href",navigate_path + (total_limit - 1) + navigate_request);
	}
	if(total_limit > 3)
		total_limit = 3;
	for(for_run=0;for_run<total_limit;for_run++){
		var age_option = document.createElement("span");
		age_option.setAttribute("class","navigate_block");
		var anchor_option = document.createElement("a");
		if((for_run + navigate_data_pid - limiter) == navigate_data_pid){
			// age_option.style.backgroundColor = "yellow";
			anchor_option.setAttribute("class","navigate_block elm_sel");
		}else{
			anchor_option.setAttribute("class","navigate_block");
			anchor_option.setAttribute("href",navigate_path + (for_run + navigate_data_pid - limiter) + navigate_request);
		}
		anchor_option.innerHTML = ((for_run + navigate_data_pid - limiter) * navigate_data_jump + 1) + "--" + (for_run + navigate_data_pid + 1 - limiter) * navigate_data_jump;
		age_option.appendChild(anchor_option);
		navigate_range.appendChild(anchor_option);
	}
};


/** Setting menu "active" definition for class selector, using recursive to "walk" on menu "tree" **/
function setMenuActiveLink(menuObj){
	var nodeID = 0;
	while(menuObj.children[nodeID] != undefined){
		setMenuActiveLink(menuObj.children[nodeID]);
		nodeID++;
	}
	if(menuObj.nodeName.toUpperCase() == "A"){
		/** This one is for relative path **/
		// if(getUrl.path == menuObj.getAttribute("href"))
		/** This one is for absolute path **/
		if(getUrl.full == menuObj.getAttribute("href") || getUrl.full + "/" == menuObj.getAttribute("href"))
			menuObj.setAttribute("class","active");
	}
	return;
};

/** Fills given object "span" elements values if 'data-cust' and 'data-value' exists and given under custData the 'data-gender' is basically optional**/
function setSpanCustValues(s_object){
	var span_elems = s_object.getElementsByTagName("span");
	/** this one may be replaced with innerHTML because nothing is really happens to this object**/
	var set_data_value = ('innerText' in span_elems[0]) ? 'innerText' : 'textContent';
	var data_cust,data_value,data_gender;
	for (key in span_elems){
		if (key < span_elems.length){
			// if(span_elems[key].className == "orn_sub_cnt" && span_elems[key].getAttribute("data-cust") != null ){
			data_cust = span_elems[key].getAttribute("data-cust");
			data_value = span_elems[key].getAttribute("data-value");
			data_gender = span_elems[key].getAttribute("data-gender");
			/** check if data cust is set and if such exists in user data array **/
			if(data_cust != null && data_value != null ){
				if(data_cust == 'user_city'){
					span_elems[key][set_data_value] = custCity[data_value] ? custCity[data_value][1] : custCity[5000][1];
				}else if(custData[data_cust]){
					/** default is 1 for man type **/
					var is_gender = (data_gender) ? data_gender : 1;
					span_elems[key][set_data_value] = custData[data_cust][is_gender] ? custData[data_cust][is_gender][data_value-1] : custData[data_cust][1][data_value-1];
				}
				// console.log(span_elems[key].getAttribute("data-cust"));
			}
		}
	}
};

/** Simple search block instances note for dependences **/
function setSearchSimple(){
	var srch_fr = document.getElementById("srch_fr");
	var srch_to = document.getElementById("srch_to");
	var srch_exe = document.getElementById("srch_exe");
	var srch_gnd = document.getElementById("srch_gnd");
	var srch_per = document.getElementById("srch_per");
	var srch_dstrct = document.getElementById("srch_dstrct");
	fillCustDataOption(srch_dstrct,'user_district');
	/** Populate age value for search block selection **/
	fillNumericOption(srch_fr,18,99);
	fillNumericOption(srch_to,18,99);
	/** default search value **/
	srch_to.value = 99;
	/** check if custom search were set **/
	if(getUrl.vars){
		/** check against request array values and numerical validity **/
		if(getUrl.vars.user_age_to && !isNaN(getUrl.vars.user_age_to))
			srch_to.value = getUrl.vars.user_age_to;
		if(getUrl.vars.user_age_from && !isNaN(getUrl.vars.user_age_from))
			srch_fr.value = getUrl.vars.user_age_from;
		if(getUrl.vars.srch_gnd && !isNaN(getUrl.vars.srch_gnd))
			srch_gnd.value = getUrl.vars.srch_gnd;
		if(getUrl.vars.user_gender && !isNaN(getUrl.vars.user_gender))
			srch_per.value = getUrl.vars.user_gender;
		if(getUrl.vars.srch_dstrct && !isNaN(getUrl.vars.srch_dstrct))
			srch_dstrct.value = getUrl.vars.srch_dstrct;
	}
	/** Search block age from change updating age to **/
	addEvent(srch_fr,'change', function(){
		if(srch_fr.value > srch_to.value)
			srch_to.value = srch_fr.value;
		for(age=18;age<=99;age++){
			if(srch_fr.value > (age))
				srch_to.options[age-18].disabled = true;
			else
				srch_to.options[age-18].disabled = false;
		}
	});
	/** Search block click to start the search event **/
	addEvent(srch_exe,'click', function(scope){
		cancelElementEvent(scope);
		var date = new Date();//Date.UTC(reg_birth_yy.value,reg_birth_mm.value-1,reg_birth_dd.value));
		var convertedDateFrom =""+date.getUTCFullYear()-srch_fr.value + "-" + (date.getUTCMonth()+1) + "-" + date.getUTCDate();
		var convertedDateTo =""+date.getUTCFullYear()-srch_to.value-1 + "-" + (date.getUTCMonth()+1) + "-" + date.getUTCDate();
		/** Those are basic search parameters and check for any perpended **/
		var params={user_age_from : srch_fr.value,user_age_to : srch_to.value};
		(srch_gnd.value) ? params['srch_gnd']= srch_gnd.value : "" ;
		(srch_per.value) ? params['user_gender']= srch_per.value : "" ;
		(srch_dstrct.value) ? params['srch_dstrct']= srch_dstrct.value : "" ;
		hiddenGetUrl('/'+getUrl['lang']+'/users/search/0',params);
	});
};

/** NOTE FOR EDIT UPDATE USER ONLY UNDER PROFILE DIR **/
var profileEdit = {
	v_profEd:"",
	profile_stack_update:{},
	user_interpersonal_stat:"",
	user_looking_for:"",
	user_about_me:"",
	user_height:"",
	user_smokes:"",
	user_face:"",
	user_body:"",
	user_name:"",
	user_city:"",
	user_district:"",
	user_city_hidden:"",
	profile_update_title:"",
	profile_update_save:"",
	profile_update_cancel:"",
	init : function(){
		v_profEd = this;
		v_profEd.user_interpersonal_stat = document.getElementById("user_interpersonal_stat");
		v_profEd.user_looking_for = document.getElementById("user_looking_for");
		v_profEd.user_about_me = document.getElementById("user_about_me");
		v_profEd.user_height = document.getElementById("user_height");
		v_profEd.user_smokes = document.getElementById("user_smokes");
		v_profEd.user_face = document.getElementById("user_face");
		v_profEd.user_body = document.getElementById("user_body");
		v_profEd.user_name = document.getElementById("user_name");
		v_profEd.user_city = document.getElementById("user_city");
		v_profEd.user_district = document.getElementById("user_district");
		v_profEd.profile_update_title = document.getElementById("profile_update_title");
		v_profEd.profile_update_save = document.getElementById("profile_update_save");
		v_profEd.profile_update_cancel = document.getElementById("profile_update_cancel");
		/** Fill out District's or states, according to selected **/
		fillCustDataOption(v_profEd.user_district,'user_district');
		/** Fill out and populate district and city respectively in hidden select object due to fucking chrome bug **/
		var distObj = 0;
		v_profEd.user_city_hidden = document.createElement("select");
		while(distObj < v_profEd.user_district.children.length){
			var select_optgroup = document.createElement("optgroup");
			select_optgroup.setAttribute("label",v_profEd.user_district.children[distObj].innerHTML);
			select_optgroup.setAttribute("value",v_profEd.user_district.children[distObj].value);
			v_profEd.user_city_hidden.appendChild(select_optgroup);
			distObj++;
		}
		for(var run in mapCity){
			var select_option = document.createElement("option");
			select_option.innerHTML = custCity[mapCity[run]][1];
			select_option.setAttribute("value",mapCity[run]);
			select_option.setAttribute("data-cust",mapCity[run]);
			/** Check if object not belongs to current district and hide it **/
			v_profEd.user_city_hidden.children[custCity[mapCity[run]][0]-1].appendChild(select_option);
		}
		v_profEd.user_city.appendChild(v_profEd.user_city_hidden.children[v_profEd.user_district.getAttribute("data-cust")-1].cloneNode(true));
		v_profEd.user_district.value = v_profEd.user_district.getAttribute("data-cust");
		v_profEd.user_city.value = v_profEd.user_city.getAttribute("data-cust");
		/** The next both event bidding are absolutely depended so i don't use regular profileStackSet note it's comment! **/
		addEvent(v_profEd.user_city,"change", function(scope){
			var evnt = getEventTarget(scope);
			v_profEd.profile_stack_update['user_city'] = evnt.value;
			v_profEd.profile_stack_update['user_district'] = v_profEd.user_district.value;
		});
		addEvent(v_profEd.user_district,'change', function(scope){
			var evnt = getEventTarget(scope);
			/** Hidden city object is starting from 0 and our is from 1 **/
			v_profEd.changeDistrict(evnt.value-1);
			v_profEd.profile_stack_update['user_district'] = evnt.value;
			v_profEd.profile_stack_update['user_city'] = v_profEd.user_city.value;
			// v_profEd.changeDistrict(v_profEd.profileStackSet(scope).value);
		});
		/** Check if user changed his city **/
		//addEvent(v_profEd.user_about_me,"change",v_profEd.profileStackSet);
		/** Fill inter select options and Check if user define his interpersonal status if not set it to default **/
		fillCustDataOption(v_profEd.user_interpersonal_stat,'user_inter',v_profEd.user_interpersonal_stat.getAttribute("data-gender"));
		if(v_profEd.user_interpersonal_stat.getAttribute("value"))
			v_profEd.user_interpersonal_stat.value = v_profEd.user_interpersonal_stat.getAttribute("value");
		else
			v_profEd.user_interpersonal_stat.value = 1;
		addEvent(v_profEd.user_interpersonal_stat,'change', function(){
			// v_profEd.profile_stack_update['user_inter'] = v_profEd.user_interpersonal_stat.selectedIndex;
			v_profEd.profile_stack_update['user_inter'] = v_profEd.user_interpersonal_stat.value;
		});
		
		
		/** Fill inter select options and Check if user define smoking if not set it to default **/
		fillCustDataOption(v_profEd.user_smokes,'user_smokes');
		if(v_profEd.user_smokes.getAttribute("value"))
			v_profEd.user_smokes.value = v_profEd.user_smokes.getAttribute("value");
		else
			v_profEd.user_smokes.value = 1;
		addEvent(v_profEd.user_smokes,'change', function(){
			v_profEd.profile_stack_update['user_smokes'] = v_profEd.user_smokes.value;
		});
		/** Fill inter select options and Check if user define his face if not set it to default **/
		fillCustDataOption(v_profEd.user_face,'user_face');
		if(v_profEd.user_face.getAttribute("value"))
			v_profEd.user_face.value = v_profEd.user_face.getAttribute("value");
		else
			v_profEd.user_face.value = 4;
		addEvent(v_profEd.user_face,'change', function(){
			v_profEd.profile_stack_update['user_face'] = v_profEd.user_face.value;
		});
		
		/** Fill inter select options and Check if user define his body if not set it to default **/
		fillCustDataOption(v_profEd.user_body,'user_body');
		if(v_profEd.user_body.getAttribute("value"))
			v_profEd.user_body.value = v_profEd.user_body.getAttribute("value");
		else
			v_profEd.user_body.value = 4;
		addEvent(v_profEd.user_body,'change', function(){
			v_profEd.profile_stack_update['user_body'] = v_profEd.user_body.value;
		});
		
		
		
		
		
		
		/** Check if user define his height if not set it to default **/
		fillNumericOption(v_profEd.user_height,100,270);
		if(v_profEd.user_height.getAttribute("value"))
			v_profEd.user_height.value = v_profEd.user_height.getAttribute("value");
		else
			v_profEd.user_height.value = 170;
		addEvent(v_profEd.user_height,'change', function(){
			v_profEd.profile_stack_update['user_height'] = v_profEd.user_height[v_profEd.user_height.selectedIndex].value;
		});
		/** Check if user changed his name and if it's correct for fire events **/
		if(v_profEd.user_name.value.length <= 2 || v_profEd.user_name.value.length > 30)
			v_profEd.user_name.setAttribute("data-css","wrong");
		addEvent(v_profEd.user_name,"change",v_profEd.profileUserName);
		addEvent(v_profEd.user_name,"keyup",v_profEd.profileUserName);
		addEvent(v_profEd.user_name,"paste",v_profEd.profileUserName);
		/** Check if user changed his about himself **/
		addEvent(v_profEd.user_about_me,"change",v_profEd.profileStackSet);
		addEvent(v_profEd.user_about_me,"keyup",v_profEd.profileStackSet);
		addEvent(v_profEd.user_about_me,"paste",v_profEd.profileStackSet);
		/** Check if user changed his looking for **/
		addEvent(v_profEd.user_looking_for,"change",v_profEd.profileStackSet);
		addEvent(v_profEd.user_looking_for,"keyup",v_profEd.profileStackSet);
		addEvent(v_profEd.user_looking_for,"paste",v_profEd.profileStackSet);
		/** User canceling any editing or just exits **/
		addEvent(v_profEd.profile_update_cancel,"click",function(){
			if(window.opener) window.close(); 
			else  history.back(-1);
		});
		/** User saves his updated fields **/
		addEvent(v_profEd.profile_update_save,"click",function(scope){
			cancelEventBubble(scope);
			cancelEventDefault(scope);
			var params={};
			var ready_flag = false;
			for(var key in v_profEd.profile_stack_update){
				params[key] = encodeURIComponent(v_profEd.profile_stack_update[key]);
				ready_flag = true;
			}
			if(ready_flag){
				var callback = function(update_result){
					if(update_result == 'SUCCESS'){
						/** If we can't reload opener clean resubmitting **/
						v_profEd.profile_stack_update={};
						v_profEd.profile_update_title.innerHTML = langObj('UPDATE_PROFILE');
						if(window.opener){
							window.opener.location.reload();
							self.close();
						}
						if(window.parent.opener){
							window.parent.opener.location.reload();;
							self.close();
						}
					}else{
						v_profEd.profile_update_title.innerHTML = langObj(update_result);
						v_profEd.profile_update_title.setAttribute("data-css","wrong");
					}
				};
				postData('/profile/update',params, callback);
			}
			else{
				v_profEd.profile_update_title.innerHTML = langObj('UPDATE_NOTHING');
				v_profEd.profile_update_title.setAttribute("data-css","wrong");
			}
		});
	},
	/** Set new cities list for selected district, clones the hidden OPTGROUP and removes current **/
	changeDistrict : function(curDis){
		v_profEd.user_city.removeChild(v_profEd.user_city.children[0]);
		v_profEd.user_city.label = v_profEd.user_city_hidden.children[curDis].firstChild.label;
		v_profEd.user_city.appendChild(v_profEd.user_city_hidden.children[curDis].cloneNode(true));
	},
	/** Add any value to update in profile that don't depends in checking **/
	profileStackSet : function(evnt){
		var evnt = getEventTarget(evnt);
		v_profEd.profile_stack_update[evnt.id] = evnt.value;
		return evnt;
	},
	/** Check if user name is fit's minimal pattern and add it **/
	profileUserName :function(){
		if(v_profEd.user_name.value.length <=2 || v_profEd.user_name.value.length > 30)
			// NEDD TO ADD SOME MESSAGE 
			v_profEd.user_name.setAttribute("data-css","wrong");
		else{
			v_profEd.user_name.setAttribute("data-css","");
			v_profEd.profile_stack_update['user_name'] = v_profEd.user_name.value;
		}
	}
};


/** NOTE FOR update new pass ONLY UNDER PROFILE DIR  **/
/**
* Prepare login forgot password block for submitting
*/
function setChangePassword(){
	var profile_chg_pass_title = document.getElementById("profile_chg_pass_title");
	var profile_chg_pass_old = document.getElementById("profile_chg_pass_old");
	var profile_chg_pass_new = document.getElementById("profile_chg_pass_new");
	var profile_chg_pass_rep = document.getElementById("profile_chg_pass_rep");
	var profile_chg_pass_submit = document.getElementById("profile_chg_pass_submit");
	/** check all data before submitting it to server **/
	addEvent(profile_chg_pass_submit,'click', function(scope){
		cancelEventBubble(scope);
		cancelEventDefault(scope);
		var pass_old_ok = false,pass_new_ok = false,pass_new_rep_ok = false;
		/** Will color the title because the user should be notified anyway **/
		profile_chg_pass_title.style.color = "#F00";
		/** check for minimal password length **/
		if(profile_chg_pass_old.value.length <= 4 || profile_chg_pass_new.value.length <= 4 || profile_chg_pass_rep.value.length <= 4){
			profile_chg_pass_title.innerHTML = langObj('PASSWORD_SHORT');
			return;
		}
		if(profile_chg_pass_new.value != profile_chg_pass_rep.value){
			profile_chg_pass_title.innerHTML = langObj('PASSWORD_NOT_MATCH');
			return;
		}
		
		// SUSCCESS Change SHOW MESSAGE THAT THE PASSWORD WAS changed !!!
		
		/** minimal is ok let's request passwords change **/
		var callback = function(change_result){
			if(change_result == 'SUCCESS')
				profile_chg_pass_title.innerHTML = langObj('PASSWORD_CHANGED');
			else{
				profile_chg_pass_title.innerHTML = langObj(change_result);
			}
		};
		postData('/login/changepassword',{change_pass_old:profile_chg_pass_old.value,change_pass_new:profile_chg_pass_new.value,change_pass_rep:profile_chg_pass_rep.value}, callback);
	});
	addEvent(profile_chg_pass_show,'click', function(scope){
		cancelEventBubble(scope);
		cancelEventDefault(scope);
		alertBlock(true,'profile_chg_pass');
	});
};

/** NOTE FOR set new pass ONLY UNDER PROFILE DIR  **/
/**
* Prepare password forgot block for submitting
*/
function setPasswordForgot(){
	var profile_new_pass_title = document.getElementById("profile_new_pass_title");
	var profile_new_pass_new = document.getElementById("profile_new_pass_new");
	var profile_new_pass_rep = document.getElementById("profile_new_pass_rep");
	var profile_new_pass_submit = document.getElementById("profile_new_pass_submit");
	var profile_new_pass_form = document.getElementById("profile_new_pass_form");
	/** check all data before submitting it to server **/
	addEvent(profile_new_pass_submit,'click', function(scope){
		cancelEventBubble(scope);
		cancelEventDefault(scope);
		/** Will color the title because the user should be notified anyway **/
		profile_new_pass_title.style.color = "#F00";
		/** check for minimal password length **/
		if(profile_new_pass_new.value.length <= 4 || profile_new_pass_rep.value.length <= 4){
			profile_new_pass_title.innerHTML = langObj('PASSWORD_SHORT');
			return;
		}
		if(profile_new_pass_new.value != profile_new_pass_rep.value){
			profile_new_pass_title.innerHTML = langObj('PASSWORD_NOT_MATCH');
			return;
		}
		/** minimal is ok let's request passwords change **/
		var callback = function(change_result){
			if(change_result == 'SUCCESS'){
				/** on success clean inner HTML and show home link to login **/
				profile_new_pass_title.innerHTML = langObj('PASSWORD_CHANGED');
				profile_new_pass_form.innerHTML = "";
				var a_elm = document.createElement('a');
				a_elm.setAttribute("href",getUrl.origin);
				a_elm.innerHTML = langObj('NAVIGATE_HOME');
				profile_new_pass_form.appendChild(a_elm);
			}else{
				profile_new_pass_title.innerHTML = langObj(change_result);
			}
		};
		postData(getUrl.path,{change_pass_new:profile_new_pass_new.value,change_pass_rep:profile_new_pass_rep.value}, callback);
	});
};

/** NOTE FOR IMAGES ONLY UNDER PROFILE DIR  **/
var profileImages = {
	thaz:"",
	/** defined vara **/
	prof_images_list:"",
	output_format:"jpg",
	/** check if profile images and upload is present, assuming that everything in it's place **/
	profile_images:"",
	profile_images_upload:"",
	profile_images_add:"",
	img_upld_msg:"",
	img_upld_adven_img:"",
	img_upld_adven_sbmt:"",
	img_upld_adven_file:"",
	img_upld_adven_open:"",
	img_upld_simpl_file:"",
	img_upld_simpl_sbmt:"",
	img_upld_simpl_ifrm:"",
	/** Virtual ghost image for image manipulation **/
	ghost_image:"",
	/** initialization/construct basic, please note for dependencies not just the basic but in image manipulator to! **/
	init : function(){
		thaz = this;
		/** check if profile images and upload is present, assuming that everything in it's place **/
		thaz.profile_images = document.getElementById("profile_images");
		thaz.profile_images_upload = document.getElementById("profile_images_upload");
		thaz.profile_images_add = document.getElementById("profile_images_add");
		thaz.img_upld_msg = document.getElementById("img_upld_msg");
		thaz.img_upld_adven_img = document.getElementById("img_upld_adven_img");
		thaz.img_upld_adven_sbmt = document.getElementById("img_upld_adven_sbmt");
		thaz.img_upld_adven_file = document.getElementById("img_upld_adven_file");
		thaz.img_upld_adven_open = document.getElementById("img_upld_adven_open");
		thaz.img_upld_simpl_file = document.getElementById("img_upld_simpl_file");
		thaz.img_upld_simpl_sbmt = document.getElementById("img_upld_simpl_sbmt");
		thaz.img_upld_simpl_ifrm = document.getElementById("img_upld_simpl_ifrm");
		/** Virtual ghost image for image manipulation **/
		thaz.ghost_image = document.createElement('img');
		thaz.ghost_image.setAttribute("id","ghost_image");
		/** Once we get our objects will start to show visual appearance **/
		thaz.prof_images_list = thaz.profile_images.getAttribute("data-cust");
		thaz.prof_images_fill();
		/** adding event to profile images area **/
		addEvent(thaz.profile_images,"click",function(evn){
			var elem = getEventTarget(evn);
			var selected_one = '';
			if(elem.className == "delete"){
				// First delete the node.. we don't need it any way
				var parent=elem.parentNode;
				var deleted_image = parent.getElementsByTagName("IMG")[0].getAttribute("src").replace(getUrl.origin + '/','');
				parent.parentNode.removeChild(parent);
				/** because we deleted and existing image we need to show add new image **/
				thaz.profile_images_add.style.display = 'block';
				// if(document.getElementById('img_selected')){
					// /** if selected image is set pass it's value to verify **/
					// selected_one = document.getElementById('img_selected').nextSibling.getAttribute("src");
				// }else if(thaz.profile_images.children.length >= 2){
					// /** because user have any images set first as selected and pass to DB **/
					// selected_one = thaz.profile_images.children[0].children[2].getAttribute("src");
					// thaz.profile_images.children[0].children[1].id = "img_selected";
				// }
				selected_one = selected_one.replace(getUrl.origin + '/','');
				deleted_image = deleted_image.replace(getUrl.origin + '/','');
				/** delete profile image and set new selected **/
				postData('/profile/imgdelete',{user_img_selected:selected_one,user_img_delete:deleted_image});
			}else if(elem.className == "select" && elem.id != "img_selected"){
				var doc_div = thaz.profile_images.getElementsByTagName("div");
				for (var i = 0; i < doc_div.length; i++) {
					if (doc_div[i].className == "select") {
					  doc_div[i].id="";
					} 
				}
				var doc_img = thaz.profile_images.getElementsByTagName("img");
				var img_list='';
				for (var i = 0; i < doc_img.length; i++) {
					if(doc_img[i].id != "profile_images_add")
						img_list+='|'+doc_img[i].getAttribute("src").replace(getUrl.origin + '/','');
				}
				elem.id="img_selected";
				selected_one = elem.parentNode.getElementsByTagName("IMG")[0].getAttribute("src").replace(getUrl.origin + '/','');
				/** set selected profile image **/
				postData('/profile/imgupdate',{user_img_selected:selected_one,user_img_paths:img_list});
			}
		});
		/** check if minimal browser support to use the manipulator if yes allow advanced **/
		if(image_manipulator.init_image_manipulator()){
			/** Because of possible browser support allow to display image advanced window **/
			document.getElementById("img_upld_adven").className = "";
			/** Adding special handling to wrap the "alert_block" in order to allow DnD **/
			addEvent(thaz.profile_images_add,"click",function(){
				alertBlock(true,"profile_images_upload");
				addEvent(alert_block,"dragover",thaz.img_upld_adven_cncl);
				addEvent(alert_block,"dragend",thaz.img_upld_adven_cncl);
				addEvent(alert_block,"drop",thaz.img_upld_adven_read);
				addEvent(alert_block_close,"click",function(){
					removeEvent(alert_block,"dragover",thaz.img_upld_adven_cncl);
					removeEvent(alert_block,"dragend",thaz.img_upld_adven_cncl);
					removeEvent(alert_block,"drop",thaz.img_upld_adven_read);
				});
			});
			/** Simulate click event on img_upld_adven_open input item change **/
			addEvent(thaz.img_upld_adven_open,"change",thaz.img_upld_adven_read);
			/** Upload button event **/
			addEvent(thaz.img_upld_adven_sbmt,"click", function(){
				var callback = function(response){
					if(response != false && response != ""){
						thaz.prof_images_list = response;
						thaz.prof_images_fill();
						alert_block_close.click();
						alertBlock(true,"alert_msg",langObj('IMG_UPLOADED'),320);
						removeEvent(alert_block,"dragover",thaz.img_upld_adven_cncl);
						removeEvent(alert_block,"dragend",thaz.img_upld_adven_cncl);
						removeEvent(alert_block,"drop",thaz.img_upld_adven_read);
					 }else
						thaz.img_upld_msg.innerHTML = langObj('IMG_ERROR');
					/** clean any images to prevent garbage collection **/
					thaz.ghost_image.src = "";
					thaz.img_upld_adven_img.src = "";
					thaz.img_upld_adven_sbmt.className = "hidden";
				};
				var response = image_manipulator.upload(thaz.ghost_image, getUrl.origin + '/profile/addimage', 'file', 'new.'+thaz.output_format,callback);
			});
			addEvent(alert_block_close,"click",function(evn){
				thaz.img_upld_msg.innerHTML = langObj('IMG_SELECT');
				/** clean any images to prevent garbage collection **/
				thaz.ghost_image.src = "";
				thaz.img_upld_adven_img.src = "";
				thaz.img_upld_adven_sbmt.className = "hidden";
			});
		}else{
			/** Show simple upload window because browser not support some basics.. :( **/
			document.getElementById("img_upld_simpl").className = "";
			thaz.img_upld_simpl_sbmt.style.display = "none";
			addEvent(thaz.img_upld_simpl_file, "change", thaz.img_upld_simpl_read);
			addEvent(thaz.profile_images_add,"click",function(){
				alertBlock(true,"profile_images_upload");
			});
			/** IFrame is simulating our file upload with the return result inside **/
			addEvent(thaz.img_upld_simpl_ifrm, 'readystatechange', function(evnt){
				var evnt = getEventTarget(evnt);
				if(evnt.readyState == "complete"){
					var temp_load = thaz.img_upld_simpl_ifrm.contentDocument.body.innerHTML;
					if(temp_load != false && temp_load != ""){
						thaz.prof_images_list = temp_load;
						thaz.prof_images_fill();
						alert_block_close.click();
						// alert("Image uploaded and soon will be checked for confirmation!");
						alertBlock(true,"alert_msg",langObj('IMG_UPLOADED'),320);
					 }else
						thaz.img_upld_msg.innerHTML = langObj('IMG_ERROR');
				}
			});
			addEvent(alert_block_close,"click",function(){
				thaz.img_upld_msg.innerHTML = langObj('IMG_SELECT');
				thaz.img_upld_simpl_sbmt.style.display = "none";
				thaz.img_upld_simpl_file.value = "";
			});
		}
	},
	/** Load images to visual display and set selected including applying styles **/
	prof_images_fill : function(){
		if(thaz.prof_images_list != ""){
			var imgs=thaz.profile_images.children.length;
			while(imgs > 0 ){
				imgs--;
				if(thaz.profile_images.children[imgs].nodeName.toLowerCase() == "div")
					thaz.profile_images.removeChild(thaz.profile_images.children[imgs]);
			}
			var img_array = thaz.prof_images_list.split("|");
			var sel_img = thaz.profile_images.getAttribute("data-sel");
			if(img_array.length >= 4)
				thaz.profile_images_add.style.display = 'none';
			else
				thaz.profile_images_add.style.display = 'block';
			for(key = 1; key < img_array.length; key++) { 
				var elm_d = document.createElement("div");
				elm_d.className = "img_mid";
				var elm_i = document.createElement("img");
				/** A newly added image that has no administrator confirmation **/
				if(img_array[key].search("&") > -1)
					elm_d.style.backgroundColor = "red";
				else{
					var elm_sel = document.createElement("div");
					elm_sel.className = "select";
					elm_d.appendChild(elm_sel);
				}
				//img_array[key].replace("&", "");
				elm_i.setAttribute("src",getUrl.origin + '/' + img_array[key].replace("&", ""));
				var elm_del = document.createElement("div");
				elm_del.className = "delete";
				elm_d.appendChild(elm_del);
				elm_d.appendChild(elm_i);
				thaz.profile_images.insertBefore(elm_d,thaz.profile_images.children[0]);
				// set selected image
				if(sel_img == img_array[key]){
					elm_sel.id = "img_selected";
				}
				if(key == 3)
					return;
			}
		}
	},
	/** Execute advanced file reading and building **/
	img_upld_adven_read : function(evnt){
		elem = cancelElementEvent(evnt);
		var file = evnt.dataTransfer ? evnt.dataTransfer.files[0] : elem.files[0];
		/** Simple check if user canceling file input or some bug **/
		if(file && file.type != "image/jpeg" && file.type != "image/png" && file.type != "image/jpg")
			return;
		else{
			var reader = new FileReader();
			reader.onload = function(){
				thaz.img_upld_adven_img.src = this.result;
				thaz.img_upld_adven_img.onload = function(){
					if(thaz.img_upld_adven_img.naturalWidth < 104 || thaz.img_upld_adven_img.naturalHeight < 104){
						/** Clean image source from file,return default view and alert user **/
						thaz.img_upld_adven_img.src = "";
						thaz.img_upld_adven_img.style.width = "";
						thaz.img_upld_adven_img.style.height = "";
						thaz.img_upld_adven_sbmt.className = "hidden";
						thaz.img_upld_msg.innerHTML = langObj('IMG_SMALL');
						return;
					}else{
						if(thaz.img_upld_adven_img.naturalWidth > 700)
							thaz.img_upld_adven_img.src = image_manipulator.normalize(thaz.img_upld_adven_img,700,thaz.output_format).src;
						//ghost_image.src = img_upld_adven_img.src;
						thaz.ghost_image.src = image_manipulator.compress(thaz.img_upld_adven_img,40,thaz.output_format).src;
						thaz.img_upld_adven_sbmt.className = "";
						thaz.img_upld_msg.innerHTML = langObj('IMG_ADD');
						thaz.img_upld_adven_img.style.width = thaz.img_upld_adven_img.naturalWidth+"px";
						thaz.img_upld_adven_img.style.height = thaz.img_upld_adven_img.naturalHeight+"px";
					}
				};
			};
			if(file.type=="image/png"){
				thaz.output_format = "png";
			}
			reader.readAsDataURL(file);
		}
	},
	/** Basic file open because input field is hidden for older browsers **/
	img_upld_simpl_read : function(){
		var f_extention = thaz.img_upld_simpl_file.value.substring(thaz.img_upld_simpl_file.value.lastIndexOf(".") + 1);
		if(f_extention == "jpeg" || f_extention == "jpg" || f_extention == "png"){
			/** Show submit button **/
			thaz.img_upld_simpl_sbmt.style.display = "block";
			var path_value = thaz.img_upld_simpl_file.value;
			if(thaz.img_upld_simpl_file.value.length >= 40)
				 path_value = '..'+path_value.substring(thaz.img_upld_simpl_file.value.length -40 ,thaz.img_upld_simpl_file.value.length);
			thaz.img_upld_msg.innerHTML = path_value;
		}else{
			thaz.img_upld_simpl_sbmt.style.display = "none";
			/** clean inappropriate value **/
			thaz.img_upld_simpl_file.value = '';
			thaz.img_upld_msg.innerHTML = langObj('IMG_WRONG_TYPE');
		}
	},
	/** Simple cancel event default and propagation **/
	img_upld_adven_cncl : function(evnt){
		cancelElementEvent(evnt);
	}
};


/**
 * Image to canvas and back to image prepossessing with PHP handle
 * @constructor
 */
var image_manipulator = {
	canvs : '',
	/** Check if minimal support is exists and create canvas**/
	init_image_manipulator : function(){
		var can_init = true;
		/** Check if browser supports canvas rendering **/
		if(!window.CanvasRenderingContext2D){can_init = false;}
		/** Check if window.FileReader exists**/
		if(!('FileReader' in window)){can_init = false;}
		/** Browser supports all minimal methods **/
		if(can_init){
			this.canvs = document.createElement("canvas");
			this.canvs.setAttribute("id","hidden_canvas");
			return true;
		}else{
			return false;
		}
	},
	/**
	 * Receives an Image Object (can be JPG OR PNG) and returns a new Image Object compressed
	 * @param {Image} source_img_obj The source Image Object
	 * @param {Integer} quality The output quality of Image Object
	 * @param {String} output format. Possible values are jpg and png
	 * @return {Image} result_image_obj The compressed Image Object
	 */
	compress: function(source_img_obj, quality, output_format){
		this.canvs.width = source_img_obj.naturalWidth;
		this.canvs.height = source_img_obj.naturalHeight;
		this.canvs.getContext("2d").drawImage(source_img_obj, 0, 0,this.canvs.width,this.canvs.height);
		return this.to_data_url(this.canvs, this.setmime(output_format), quality);
	},

	normalize: function(source_img_obj, maxwidth, output_format){
		var norm_factor = maxwidth / source_img_obj.naturalWidth;
		this.canvs.width = source_img_obj.naturalWidth * norm_factor;
		this.canvs.height = source_img_obj.naturalHeight * norm_factor;
		this.canvs.getContext("2d").drawImage(source_img_obj, 0, 0,this.canvs.width,this.canvs.height);
		return this.to_data_url(this.canvs, this.setmime(output_format));
	},
	/** Return or JPEG or PNG mime type **/
	setmime: function(mime_format){
		var mime_type = "image/jpeg";
		if(typeof mime_format !== "undefined" && mime_format=="png")
			return "image/png";
		else
			return "image/jpeg";
	},
	/** Simple convert to data URL and return object**/
	to_data_url: function(item, mime_type, quality){
		quality = typeof quality !== 'undefined' ? quality : 100;
		var newImageData = item.toDataURL(mime_type, quality/100);
		var result_image_obj = new Image();
		result_image_obj.src = newImageData;
		return result_image_obj;
	},
	/**
	 * Receives an Image Object and upload it to the server via ajax
	 * @param {Image} compressed_img_obj The Compressed Image Object
	 * @param {String} The server side url to send the POST request
	 * @param {String} file_input_name The name of the input that the server will receive with the file
	 * @param {String} filename The name of the file that will be sent to the server
	 * @param {function} successCallback The callback to trigger when the upload is successful.
	 * @param {function} (OPTIONAL) errorCallback The callback to trigger when the upload failed.
	 * @param {function} (OPTIONAL) duringCallback The callback called to be notified about the image's upload progress.
	 * @param {Object} (OPTIONAL) customHeaders An object representing key-value  properties to inject to the request header.
	 */
	upload: function(compressed_img_obj, upload_url, file_input_name, filename, successCallback, errorCallback, duringCallback, customHeaders){
		document.body.style.cursor = "wait";
		this.canvs.width = compressed_img_obj.naturalWidth;
		this.canvs.height = compressed_img_obj.naturalHeight;
		var ctx = this.canvs.getContext("2d").drawImage(compressed_img_obj, 0, 0);
		//ADD sendAsBinary compatibility to older browsers
		if (XMLHttpRequest.prototype.sendAsBinary === undefined) {
			XMLHttpRequest.prototype.sendAsBinary = function(string) {
				var bytes = Array.prototype.map.call(string, function(c) {
					return c.charCodeAt(0) & 0xff;
				});
				try{
					this.send(new Uint8Array(bytes));
				} catch (e) {
					this.send(new Uint8Array(bytes).buffer);
				}
			};
		}
		var type = "image/jpeg";
		if(filename.substr(-4)==".png"){
			type = "image/png";
		}
		var data = this.canvs.toDataURL(type);
		data = data.replace('data:' + type + ';base64,', '');
		var xhr = new XMLHttpRequest();
		xhr.open('POST', upload_url, true);
		var boundary = 'someboundary';
		xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
		// Set custom request headers if customHeaders parameter is provided
		if (customHeaders && typeof customHeaders === "object") {
			for (var headerKey in customHeaders){
				xhr.setRequestHeader(headerKey, customHeaders[headerKey]);
			}
		}
		// If a duringCallback function is set as a parameter, call that to notify about the upload progress
		if (duringCallback && duringCallback instanceof Function) {
			xhr.onprogress = function (evt) {
				if (evt.lengthComputable) {  
					return (evt.loaded / evt.total)*100;  
				}
			};
		}
		xhr.sendAsBinary(['--' + boundary, 'Content-Disposition: form-data; name="' + file_input_name + '"; filename="' + filename + '"', 'Content-Type: ' + type, '', atob(data), '--' + boundary + '--'].join('\r\n'));
		xhr.onreadystatechange = function() {
			if (this.readyState == 4){
				document.body.style.cursor = "";
				if(this.status == 200){
					successCallback(this.responseText);
				}else{
					successCallback(false);
				}
			}
		};
	}
};