var GLOBAL_USER_NAME = null;
var GLOBAL_HOST = null;
function $(id) {
	return document.getElementById(id);
}

function isEmail(string) {
	return /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(string);
}
function isWebsite(string){
	if (string.search(/^(http:\/\/)?(((\w|-)+\.)+([a-z0-9]){2,}\/?)$/i) != -1)
		return true;
	else return false;
    
}

function lock_form_controls(frm, disable, clear_edits) {
	for(i = 0; i < frm.elements.length; i++) {
		lock_control(frm.elements[i], disable, clear_edits);
	}
}

function lock_control(control, disable, clear) {
	if (disable) {
		if (control.disabled != "undefined") {
			control.disabled = true;
		}
	} else {
		if (control.disabled != "undefined") {
			control.disabled = false;
		}
		if (clear) {
			type = control.tagName.toLowerCase();
			if (type == "textarea" || (type == "input" && control.type.toLowerCase() == "text")) {
				control.value = "";
			}
		}
	}
}

function switch_ctrl_enable(el, enabled, capt) {
	if (typeof el != "object") el = document.getElementById(el);
	if (!el) return;
    
	el.disabled = !enabled;
	el.value = capt;
}

function hideStatus(answer, answer2, element_id, value) {
	if (value != answer && value != answer2) {
		$(element_id).style.display = "none";
	} else {
		$(element_id).style.display = "";
	}
}

function customMultipleMenu(narray) {
	var sstyle = "background:#fff;" +
	"overflow: auto;" +
	"height:7.1em;" +
	"font-size: 8pt;" +
	"border-left:1px solid #404040;" +
	"border-top:1px solid #404040;" +
	"border-bottom:1px solid #d4d0c8;" +
	"border-right:1px solid #d4d0c8;";

	var sHTML = "";
	var div_s = "<div style='"+ sstyle +"'>";
	var div_f = "</div>";

	sHTML += div_s;
	for (var i = 0; i < narray.length; i++) {
		sHTML += "<label for='cb"+ i +"' style='padding-right:3px;display:block;'>";
		sHTML += "<input name=\"emails[]\" value=\""+narray[i]+"\" type=\"checkbox\" checked id='cb"+ i  +"'/>";
		sHTML += narray[i];
		sHTML += "</label>";
	}
	sHTML += div_f;
	return sHTML;
}

function noChildren(answer, objId, showId, value) {
	if (answer != value) {
		$(objId).style.display = "none";
		$(showId).style.display = "";
	} else {
		$(objId).style.display = "";
		$(showId).style.display = "none";
	}
}

function clickClear(object_id, value) {
	$(object_id).onclick = function() {
		$(object_id).value = "";
	}
}

function statusIn (answer, univ_id, univ_div) { 
	if (answer == "1") {
		$(univ_div).style.display = "none";
		$(univ_id).style.display = "none";
	} else {
		$(univ_id).style.display = "";
		$(univ_div).style.display = "";
	}
}

// Error if ajax connect is lost
var errFunc = function(t) {
	alert('Sorry please contact with administrator');
}

/**
 *  Send PIN by SMS Api
 */
var handlerFunc = function(t) {
	var resp = t.responseText;
	if (resp == "unvalidate") {
		alert('Sorry - Invalid mobile number\nMobile Number Format: e.g. 448311234567');
	} else if (resp == "ok"){
		alert('Please Wait, Pin being sent via SMS');
	} else alert("You must wait sms.");
}

function getPin(host, id) {
	number = "&phone=" + $(id).value;
	new Ajax.Request(host + number, {
		onSuccess:handlerFunc,
		onFailure:errFunc
	});
}

/**
 *  Check PIN 
 */
var handlerFuncPin = function(t) {
	var resp = t.responseText;
	if (resp == "correct") {
		var t = document.getElementById('sms_reg');
		t.style.display = 'none';
		var t = document.getElementById('verif');
		t.innerHTML = 'Yes';
	} else if(resp == "ok") {
		document.location = 'index.php?action=sms_send';
	} else if(resp == "cor") {
		var t = document.getElementById('verif');
		t.innerHTML = '<b>Thanks, you are now verified.</b>';
	} else {
		alert("Sorry it is incorrect");
	}
}

function getSubmit(host, id) {
	key = "&key=" + $(id).value;
	new Ajax.Request(host + key, {
		onSuccess: handlerFuncPin,
		onFailure:errFunc
	});
}

/**
 * Import address book with AJAX
 */
var handlerFuncImport = function(t) {
	var response = t.responseText;
	if (response == "unimport") {
		$('import_msg').innerHTML = "Sorry incorrect operation";
	} else {
		var emails = response.split("\n");
		$('list_users').innerHTML = customMultipleMenu(emails);
		$('import_msg').innerHTML = "";
	}
}

function importAddress(host, abook, ab_email, ab_password) {
	var email = $(ab_email).value;
	var passw = $(ab_password).value;
	var abook = $(abook).value;
	var param = "&address_book=" + abook + "&address_book_email=" + email + "&address_book_password=" + passw;
	$('import_msg').innerHTML = "Please wait";
	new Ajax.Request(host + param, {
		onSuccess: handlerFuncImport,
		onFailure:errFunc
	});
}

/**
 * Check URL Availability
 */
var handlerFuncCUA = function(t) {
	var response = t.responseText;
    
	if (response == "noexists") {
		$('check_url').innerHTML = "Online name is available";
	} else if (response == "uncorrect") {
		$('check_url').innerHTML = "Online name is empty";
	} else {
		$('check_url').innerHTML = "Online name is not available";
	}
}

/**
 *  Check URL Availability
 */
function checkURLAvailability(host, id) {
    
	key = "?action=ajax&page=check_url&name=" + $(id).value;
	$('check_url').innerHTML = "";
	new Ajax.Request(host + key, {
		onSuccess: handlerFuncCUA,
		onFailure:errFunc
	});
}

/**
 * Get paramters from form
 */
function serializeForm(f) {
	var params = "";

	for (var i = 0; i < f.elements.length; i++) {

		if (params != "") params += "&";

		if (f.elements[i].type == "radio"){
			if (f.elements[i].checked==true){
				params += f.elements[i].name;
				params += "=";

				params += f.elements[i].value;
			}
		}
		else{
			params += f.elements[i].name;
			params += "=";
			if (f.elements[i].type == "checkbox") {
				params += f.elements[i].checked;
			}
			else
			{
				params += escape(f.elements[i].value);
			}
		}

	}
	return params;
}

/**
 * Control Panel Update form with AJAX
 * host - url for server
 * form - html form
 * error_id - id for update 
 */

var handlerFuncUpdate = function(t) {
	var response = t.responseText;
    
	if (response == "error") {
		alert("Sorry - Update profile information is incorrect");
	} else {
		alert("Successful");
	}
}

function formUpdate(host, f, error_id) {
	var arguments = "action=ajax&page=controlpanel&" + serializeForm(f);
	new Ajax.Request(host, {
		method:'post',
		postBody: arguments,
		onSuccess: handlerFuncUpdate, 
		onFailure:errFunc
	});
                      
}

/**
 * Settings on Panel Update parameter with AJAX
 * host - url for server
 * form - html form
 * error_id - id for update 
 */
var handlerFuncUParam = function(t) {
	var response = t.responseText;
	//    alert(response);
	if (response == "error") {
		alert("Sorry - Update profile information is incorrect");
	} else if (response == "avalilable") {
		alert("Online name is not available");
	} else if (response == "email_avalilable") {
		alert("User email is not available");
	} else if (response == "unpassword") {
		alert("Incorrect old password");
	} else {
		alert("Successful");
	}
}

function updateParameter(host, state, value_id) {
	var arguments = "action=ajax&page=updateparameter" +
	"&state=" + state +
	"&value=" + $(value_id).value;
	new Ajax.Request(host, {
		method:'post',
		postBody: arguments,
		onSuccess: handlerFuncUParam, 
		onFailure:errFunc
	});
}

function updatePassword(host, f) {
	var alert_msg = "";
	if (f.new_password.value != f.confirm_password.value) {
		alert_msg = "Passwords don't match\n";
	}

	if (f.new_password.value.length < 3)
		alert_msg = "The Password length is wrong\n";

	if (alert_msg != "") {
		alert(alert_msg);
		return;
	}
	var arguments = "action=ajax&page=updateparameter&state=password&" + serializeForm(f);
	new Ajax.Request(host, {
		method:'post',
		postBody: arguments,
		onSuccess: handlerFuncUParam, 
		onFailure:errFunc
	});
}

var HFVoted = function(t) {
	var response = t.responseText;
	alert(response);
}


var HFVote = function(t) {
	var response = t.responseText;
   
	if (response == "ok") {
		disableForm('voteUser');
	}

	if (response == "ok" && GLOBAL_USER_NAME != null) {
		var arguments = "?action=ajax&page=vote_panel&user_name=" + GLOBAL_USER_NAME;
		new Ajax.Updater('vote_panel', GLOBAL_HOST + arguments, {
			onSuccess: HFVote,
			onFailure:errFunc
		});
	}
}

function voteUser(host, f, user_name) {
	var arguments = "action=ajax&page=vote&" + serializeForm(f);
	new Ajax.Request(host, {
		method:'post',
		postBody: arguments,
		onSuccess: HFVote, 
		onFailure:errFunc
	});
	GLOBAL_HOST = host;
	GLOBAL_USER_NAME = f.id.value;
	return false;
}
/**
 * Disable all parameters
 */
function disableForm(f) {
	var f = $(f);
	for (var i = 0; i < f.elements.length; i++) {
		f.elements[i].disabled = true;
	}
}

function confirmationOperation(form, type_operation) {
	if (typeof(form) == 'undefined') {
		return;
	}

	if (type_operation == "blocked") {
		form.operation.value = "blocked";
		if (window.confirm("Do you really want blocked user?")) {
			form.submit();
		}
	} else if (type_operation == "favorite") {
		form.operation.value = "blocked";
		form.submit();
	} else if (type_operation == "invite") {
		form.operation.value = "invite";
		form.submit();
	}
}

var HFBlock = function(t) {
	var response = t.responseText;
}

var HFBlockNote = function(t) {
	var response = t.responseText;
}



function unblockUser(host, id, uname) {
	var arguments = "?action=ajax&page=block&name=" + uname;
	new Ajax.Updater(id, host + arguments, {
		onSuccess: HFBlock,
		onFailure:errFunc
	});
}

function openNotesEdit(id, host, uname) {
	var arguments = "?action=ajax&page=notes_new&name=" + uname;
	var hosti = host + arguments;
	//   host = "";
	new Ajax.Updater(id, hosti, {
		onSuccess: HFBlockNote,
		onFailure:errFunc
	});
}

function sendNotesSubmit(id, host, uname, notes_edit) {
	if (typeof($(notes_edit)) == 'undefined') {
		return;
	}
	// host = "";
	var t = document.getElementById('note_status');
	var arguments = "?action=ajax&page=notes_send&name=" + uname +"&message=" + $(notes_edit).value +"&note_status=" + t.value;
	new Ajax.Updater(id, host + arguments, {
		onSuccess: HFBlock,
		onFailure:errFunc
	});
}

function deleteNotesEdit(id, host, uname, notes_edit) {
	/*if (typeof($(notes_edit)) == 'undefined') {
        return;
    }*/
	//host = "";
	var arguments = "?action=ajax&page=notes_edit&name=" + name;
	new Ajax.Updater(id, host + arguments, {
		onSuccess: HFBlock,
		onFailure:errFunc
	});
}

var HFTreads = function(t) {
	var response = t.responseText;
	if (response == "ok") {
		alert("Succesfull");
	} else if (response == "not_send") {
		alert("Please select gift(s)");
	}
}

function sendLikeTo(host, f, uname) {
	var arguments = "action=ajax&page=tl&name="+ uname +"&" + serializeForm(f);
	new Ajax.Request(host, {
		method:'post',
		postBody: arguments,
		onSuccess: HFTreads, 
		onFailure:errFunc
	});
	return false;
}

function selectGift(host, id, t, uname) {
	var arguments = "action=ajax&page=treadyas&name="+ t.name +"&check="+ t.checked;
	new Ajax.Updater(id, host, {
		method:'post',
		postBody: arguments,
		onSuccess: HFTreads, 
		onFailure:errFunc
	});
	return false;
}

function sendYouAre(host, f, uname) {
	var arguments = "action=ajax&page=tread_youare&name="+ uname +"&" + serializeForm(f);
	new Ajax.Request(host, {
		method:'post',
		postBody: arguments,
		onSuccess: HFTreads, 
		onFailure:errFunc
	});
	return false;
}

/**
 * Show text field for add new record 
 * on page confirm.php
 * @param idadd - id for show element
 */
function addEI(idadd) {
	if ($(idadd).style.display != "none") {
		return;
	}

	if (window.confirm("Do you want to create your own record?")) {
		Element.show(idadd);
	}
}

/**
 * Update website information
 * 
 *
 */
var HFDomain = function(t) {
	var response = t.responseText;
    
	if (response == "error") {
		alert("Sorry - Update website is incorrect");
	} else {
		alert("Successful");
	}
}

function updateDomain(host, f, error_id) {
	var arguments = "action=ajax&page=updateparameter&state=domain&" + serializeForm(f);
	new Ajax.Request(host, {
		method: 'post',
		postBody: arguments,
		onSuccess: HFDomain,
		onFailure:errFunc
	});
	return false;
}

function ideserve_ajax(action, id, xtra) {
	url = "index.php?action=ajax&page=ideserve_ajax&mod=" + action + "&id=" + id + "&xtra=" + xtra;
    
	new Ajax.Request(url, {
		onSuccess:share_handler_evaler,
		onFailure:errFunc
	});
}

function classifield_ajax(action, id, xtra) {
	url = "index.php?action=ajax&page=classifield_ajax&mod=" + action + "&id=" + id + "&xtra=" + xtra;
    
	new Ajax.Request(url, {
		onSuccess:share_handler_evaler,
		onFailure:errFunc
	});
}

// add video to playlist
function media_share(action, id, xtra) {
	url = "index.php?action=ajax&page=media_share&mod=" + action + "&media_id=" + id + "&xtra=" + xtra;
    
	new Ajax.Request(url, {
		onSuccess:share_handler_evaler,
		onFailure:errFunc
	});
}

var share_handler_evaler = function(t) {
	var response = t.responseText;
	eval(response);
}

function add_media_to_club(host, club_id) {
	number = "&club_id=" + club_id;
	new Ajax.Request(host + number, {
		onSuccess:share_handler_evaler
	});
}

function market_share(action, id, xtra) {
	url = "index.php";
	arguments = "action=ajax&page=market_share&mod=" + action + "&id=" + encodeURIComponent(id) + "&xtra=" + xtra;
	new Ajax.Request(url, {
		method: 'post',
		postBody: arguments,
		onSuccess:share_handler_evaler
	});
}

function render_float_div(content, mode, id, height) {
	var fdiv = document.getElementById("float_div");
	if (!fdiv) {
		new_div = document.createElement('div');
		new_div.id = 'float_div';
		document.getElementsByTagName('body')[0].appendChild(new_div);
		new_div.style.display = "none";
		new_div.style.position = "absolute";
		new_div.style.backgroundColor = "white";
		new_div.style.border = "2px solid black";
		new_div.style.textAlign = "left";
		new_div.style.zIndex = "100";
		fdiv = document.getElementById("float_div");
	}
	fdiv.innerHTML = content;
    
	if (height){
		var h = height;
	} else{
		var h = 150;
	}
    
	if (mode == "div_pos") {
		div_dim = get_dimensions(document.getElementById(id));
		fdiv.style.top = div_dim.top+'px';
		fdiv.style.left = div_dim.left+'px';
		fdiv.style.width = div_dim.width+'px';
	} else if (mode == "screen_center") {
		var w = 450;
		var dh = screen.height - screen.availHeight;
		var l = (screen.width - w) / 2;
		var t = ((screen.height - h) / 2) - dh + document.documentElement.scrollTop;
        
		fdiv.style.top = t+'px';
		fdiv.style.left = l+'px';
		fdiv.style.width = w+'px';
	} else {
		return;
	}
	fdiv.style.height = h+'px';
	fdiv.style.display = "";
}
// for bautton community life on left menu

function show_hide_left_menu_buttons(){
    
	var buttons=document.getElementById("community_buttons");
	if (buttons.style.display == "none")
		buttons.style.display = "block";
	else
		buttons.style.display = "none";

}
// for verify email address for groups
function need_email(status, id){
    
	var email=document.getElementById(id);
    
	if (email)
		if (status>100)
		{
			email.style.display='none';
		}
		else
		{
			email.style.display='block';
		}
}
function check_email_for_group(email_field,status_field, group){
	var email=document.getElementById(email_field);
	var status=document.getElementById(status_field);
	var site=document.getElementById('website');
    
	if (email && status && (!site || site.value!="") )
	{
		if (status.value<100) //need verify
		{
			if (email.value=="")
			{
				alert('Enter you email address');
				return false;
			}
			else
			{
				if (!isEmail(email.value))
				{
					alert('Email address is incorrect!');
					return false;
				}
				else
				{
					return true;
				}
			}
		}
		else
		{
			return true;
		}
	}
	return true;
}



/**
 * Check ORg email
 */


var handlerFuncCOrgE_University = function(t) {
	var response = t.responseText;
	$('univ_ver').value=response;
	checkverif();
}

var handlerFuncCOrgE_Company = function(t) {
	var response = t.responseText;
	$('comp_ver').value=response;
	checkverif();
}

function checkverif(){
	var response1=$('univ_ver').value;
	var response2=$('comp_ver').value;

	if (response1 == "false" || response2 == "false" )
		return "wait";
	if (response1 == "not_verified" ){
		alert('Invalid University Email Address');
	}
	if (response2 == "not_verified" ){
		alert('Invalid Company Email Address');
	}
	if (response1 == "not_verified" || response2 == "not_verified" )
		return false;

	if (response2 == "verified" ){
		alert('Verification email sent to Company Email Address');
	}
	if (response1 == "verified" ){
		alert('Verification email sent to University Email Address');
	}
	$('form_id').onsubmit="";
	$('form_id').submit();
	return true;
    
}

/**
 *  Check Org email
 */

function checkOrganizationEmail(host, group_id, email, website, group_title) {
    
	key = "?action=ajax&page=check_org_email&group_id=" + group_id+"&email="+escape(email)+"&website="+escape(website);
	switch (group_title){
		case 'University':
			var f=new Ajax.Request(host + key, {
				asynchronous: true ,
				onSuccess: handlerFuncCOrgE_University,
				onFailure:errFunc
			});
			break;
		case 'Company':
			var f=new Ajax.Request(host + key, {
				asynchronous: true ,
				onSuccess: handlerFuncCOrgE_Company,
				onFailure:errFunc
			});
			break;
        
	}
    
	return false;
}


function check_email_for_reg(host, group_field, group_name_field, website_field, email_field, status_field,  group_title){
    
	var group=document.getElementById(group_field);
	var group_name=document.getElementById(group_name_field);
	var website=document.getElementById(website_field);
	var email=document.getElementById(email_field);
	var status=document.getElementById(status_field);
    
	if (email.value!=""){
		if (!isEmail(email.value)){
			alert ("Check your  "+group_title+" email address");
			return false;
		}
	}
    

	if (group_name.value!=""){ // adding group
        
		if (website.value!="" && !isWebsite(website.value)){
			alert("Check "+group_title+" website address");
			return false;
		}
	}

	if (status.value>100){
		return "not_need_verification";
	}
	else
		return checkOrganizationEmail(host,group.value,email.value,website.value, group_title);
}


function openPopup(aSender, url, title, nWidth, nHeight,aScreenX,aScreenY) {
	var nScreenX, nScreenY;

	if (!aScreenX || !aScreenY) {
		nScreenX = (screen.width - nWidth) / 2;
		nScreenY = (screen.height - nHeight) / 2;
	} else {
		if (navigator.appName == "Netscape" && navigator.product == "Gecko") {
			nScreenX = aScreenX - 200;
			nScreenY = aScreenY;
		} else if (navigator.userAgent.indexOf("Opera",0) > -1) {
			nScreenX = event.clientX - 200;
			nScreenY = event.clientY ;
		} else {
			nScreenX = aScreenX - 200;
			nScreenY = aScreenY;
		}
	}

	// Open calendar
	if (window.CalendarWnd != null && !window.CalendarWnd.closed) {
		window.CalendarWnd.focus();
	}

	window.CalendarWnd = window.open(url, title,'width=' + nWidth + ',height=' + nHeight + ',left=' + nScreenX + ',top=' + nScreenY + ',screenX=' + nScreenX + ',screenY=' + nScreenY + ',resizable=yes,menubar=no,toolbar=no,scrollbars=yes');
}

function check_max_length(e, elem_value, max_length){
	//alert(elem_value.length);
	if (elem_value.length<max_length)
		return true;
	else{
		var keynum
		var keychar
		var numcheck

		if(window.event) // IE
		{
			keynum = e.keyCode
		}
		else if(e.which) // Netscape/Firefox/Opera
		{
			keynum = e.which
		}
        
		keychar = String.fromCharCode(keynum)
		numcheck = /\w/
        
		return !numcheck.test(keychar)
	}

}

function swap_visibility_by_id(_id) {
	if (typeof _id == "object") {
		var l = _id.length;
		for (i = 0; i < l; i++) {
			var el = document.getElementById(_id[i]);
			if (el)    {
				if (el.style.display == 'none') _set_visible(el);
				else _set_invisible(el);
			}
		}
	} else {
		var el = document.getElementById(_id);
		if (el)    {
			if (el.style.display == 'none') return _set_visible(el);
			else return _set_invisible(el);
		}
	}
	return false;
}

function _set_visible(el) {
	if (typeof el == "object") el.style.display = '';
	else if (document.getElementById(el)) document.getElementById(el).style.display = '';
	return false;
}

function _set_invisible(el) {
	if (typeof el == "object") el.style.display = 'none';
	else if (document.getElementById(el)) document.getElementById(el).style.display = 'none';
	return false;
}

function check_cart_fields() {
	var ship_addr = document.getElementById("ship_addr");
	if (ship_addr && ship_addr.value.length < 5) {
		alert("Shipping address field is mandatory!");
		return false;
	}
	return true;
}

function tv_operation(action, id, f) {
    
	url = "index.php?action=ajax&page=ajax_tv_operation&operation=" + action + "&id=" + id + "&";
    
	if (typeof ($(f))!= 'undefined')
		url=url+serializeForm($(f));
    
	new Ajax.Request(url, {
		onSuccess:share_handler_evaler,
		onFailure:errFunc
	});
}

function get_person(el, container, movie_id){
	new Ajax.Updater(container, 'index.php?action=ajax&page=ajax_tv_operation&operation=get_person&person_id='+el.value+'&id='+movie_id);
	el.enabled=false;
	document.getElementById(container).style.display='block';
}

function is_verifed_Ajax(action, id, xtra, verified)
{ 
	if(verified)
	{
		ideserve_ajax(action, id, xtra);
	}
	else
	{
		ideserve_ajax('Not_accepted', id, action);
	}
}

   
