function createXMLHttp() {

    if (typeof XMLHttpRequest != "undefined") {
        return new XMLHttpRequest();
    } else if (window.ActiveXObject) {
      var aVersions = [ "MSXML2.XMLHttp.5.0",
        "MSXML2.XMLHttp.4.0","MSXML2.XMLHttp.3.0",
        "MSXML2.XMLHttp","Microsoft.XMLHttp"
      ];

      for (var i = 0; i < aVersions.length; i++) {
        try {
            var oXmlHttp = new ActiveXObject(aVersions[i]);
            return oXmlHttp;
        } catch (oError) {
            //Do nothing
        }
      }
    }
    throw new Error("XMLHttp object could be created.");
}

/**
 * updateStateField()
 *
 * This function will update a state select field & state label based off
 * a country select field.  The first 5 parameters are required, the sixth
 * is optional text to be appended to the state label.
 *
 * @param string e				The country select field element ID
 * @param string l				The current language
 * @param string label			The state label ID
 * @param string s				The state select field element ID
 * @param int in_smartway		1 if used in smartway, 0 otherwise
 * @param string add				Additional text to append to the state label
 *
 * Example: updateStateField('create_event_country','name_en','event_state_label','create_event_state',1,':')
 */
function updateStateField(e,l,label,s,in_smartway,add,all_flag)
{
	var xmlhttp = createXMLHttp();
	/* Testing */
	var pos = elementPosition(document.getElementById(s+"_container"));
	var nd = document.createElement('div');
	nd.setAttribute('id', 'states_loading_msg');
	nd.className = 'webbox_rollover';
	nd.style.height = '20px';
	nd.style.top = (pos[1] + 20) + 'px';
	nd.style.left = pos[0] + 'px';
	nd.innerHTML = 'Loading states... please wait';
	document.body.appendChild(nd);
	/* Testing End  */

	var c = document.getElementById(e).value;
	var server = 'ajax_server.php';
	if(in_smartway==0)
	{
		server = 'smartway/' + server;
	}

	if(all_flag != null && all_flag > 0)
	{
		all_flag = 1;
	}
	else
	{
		all_flag = 0;
	}

	xmlhttp.open('GET',server+"?action=state_label&ajax_param_country_id="+c+"&ajax_param_lang="+l+"&ajax_param_allflag="+all_flag,true);
	xmlhttp.onreadystatechange = function() {
		if(xmlhttp.readyState == 4)
		{
			/* Testing */
			document.body.removeChild(document.getElementById('states_loading_msg'));
			/* Testing End */
			response = xmlhttp.responseText;
			var info = response.split("|");
			if(info[1] == 'disabled')
			{
				document.getElementById(s+"_container").innerHTML = '<select name="'+s+'" id="'+s+'"><option value="-">----------</option></select>';
				document.getElementById(s).disabled = true;
				document.getElementById(label).innerHTML = '';
				document.getElementById(label).innerHTML = info[2] + add;
			}
			else
			{
				document.getElementById(s).disabled = false;
				document.getElementById(s+"_container").innerHTML = '<select name="'+s+'" id="'+s+'">'+info[2]+'</select>';
				document.getElementById(label).innerHTML = info[1] + add;
			}

			/*if(info[0] == '0')
			{
				document.getElementById(zipcode).disabled = true;
			}
			else
			{
				document.getElementById(zipcode).disabled = false;
			}*/
		}
	}
	xmlhttp.send(null);
}

function openMapWindow(id)
{
	window.open('index.php?page=event_map&event_id='+id,'','width=450,height=450,resizeable=0,toolbar=0');
	return false;
}

function openWindow(url,w,h)
{
	window.open(url,'','width='+w+', height='+h+',resizeable=0, toolbar=0, statusbar=0')
}

function cancelEvent()
{
	document.cancel_event.submit();
	return false;
}

function elementPosition(param){
	var x=0, y=0;
	var obj = (typeof param == "string") ? document.getElementById(param) : param;
	if (obj) {
		x = obj.offsetLeft;
		y = obj.offsetTop;
		var body = document.getElementsByTagName('body')[0];
		while (obj.offsetParent && obj!=body){
			x += obj.offsetParent.offsetLeft;
			y += obj.offsetParent.offsetTop;
			obj = obj.offsetParent;
		}
	}
	coord = new Array(x,y);
	return coord;
}

function chat_open()
{
	var new_window = window.open('index.php?page=chat_rooms','','width=600,height=500,scrollbars=no,resizeable=no');
}

function statusEdit(div, edit)
{
	div = document.getElementById(div);
	div.style.display = 'inline';

	prefix = 'is ';
	edit = document.getElementById(edit);
	edit.value = prefix;
	edit.focus();
	set_caret_position(edit, prefix.length, edit.value.length);
}

function set_caret_position(obj,start,end)
{
	if(document.selection)
	{
		if (obj.tagName == 'TEXTAREA')
		{
			var i = obj.value.indexOf("\r", 0);
			while (i != -1 && i < end)
			{
				end--;
				if(i < start)
				{
					start--;
				}
        i = obj.value.indexOf("\r", i + 1);
			}
		}
		var range = obj.createTextRange();
		range.collapse(true);
		range.moveStart('character', start);
		if (end != undefined)
		{
			range.moveEnd('character', end - start);
		}
    range.select();
	}
	else
	{
		obj.selectionStart = start;
		var sel_end = end == undefined? start: end;
		obj.selectionEnd = Math.min(sel_end, obj.value.length);
		obj.focus();
	}
}

function statusCancel(div)
{
	div = document.getElementById(div);
	div.style.display = 'none';
}

function statusSet(div, edit, div_status, div_status_add, status_edit, status_default, name, update_home, hide_form, status_success_message, status_succcess_elem)
{
	var update_home = (update_home == null) ? true : update_home;
	var hide_form = (hide_form == null) ? true : hide_form;
	var xmlhttp = createXMLHttp();

	if (input = document.getElementById(edit))
	{
		statusText = input.value;
	}
	else
	{
		statusText = '';
	}
    statusText = statusText.substring(0, 139);

	server = 'smartway/ajax_server.php';
	xmlhttp.open('GET', server + "?action=statusSet&ajax_param_member_id=" + member_id + "&ajax_param_statusText=" + statusText, true);
	if (update_home==true)
	{
		xmlhttp.onreadystatechange = function()
		{
			if(xmlhttp.readyState == 4)
			{
				/* Testing */
				/* Testing End */
				response = xmlhttp.responseText;
				if (response > 0)
				{
					document.getElementById(div_status).innerHTML = name + ' ' + statusText;
					if (statusText.length > 0)
					{
						document.getElementById(div_status_add).innerHTML = 'a moment ago';
						document.getElementById(status_edit).innerHTML = 'edit';
					}
					else
					{
						document.getElementById(div_status).innerHTML = '';
						document.getElementById(div_status_add).innerHTML = '';
						document.getElementById(status_edit).innerHTML = status_default;
					}
				}
			}
		}
	}
	else if (status_succcess_elem != null)
	{
		xmlhttp.onreadystatechange = function()
		{
			if(xmlhttp.readyState == 4)
			{
				document.getElementById(status_succcess_elem).innerHTML = status_success_message;
			}
		}
	}
	xmlhttp.send(null);
	div = document.getElementById(div);
	if (hide_form==true)
	{
		div.style.display = 'none';
	}
}

function getCookie(c_name)
{
	if (document.cookie.length>0)
	{
	  	c_start=document.cookie.indexOf(c_name + "=");
	  	if (c_start!=-1)
	  	{
		    c_start=c_start + c_name.length+1;
		    c_end=document.cookie.indexOf(";",c_start);
		    if (c_end==-1) c_end=document.cookie.length;
		    return unescape(document.cookie.substring(c_start,c_end));
	  	}
	}
	return "";
}

function request_friends()
{
	var xmlhttp = createXMLHttp();
    window.wn_friends = new Array();

	m_id = getCookie('m_id');
	server = 'smartway/ajax_server.php';
	xmlhttp.open('GET', server + "?action=fetchfriends&ajax_param_member_id=" + m_id, true);
	xmlhttp.onreadystatechange = function()
	{
		if(xmlhttp.readyState == 4)
		{
			/* Testing */
			/* Testing End */
			out = new Array();
			response = xmlhttp.responseXML;
			if (xmlhttp.responseText=='') return;

			if (typeof response == "object")
			{
				root = response.getElementsByTagName('root').item(0);
				for (iNode=0;iNode<root.childNodes.length;iNode++)
				{
                	node = root.childNodes.item(iNode);
                	if (!node.childNodes.item(11)) ie = true;
                	else ie = false;
                	memberElem = new Array();
                	memberElem['member_id'] = node.childNodes.item((ie?0:1)).childNodes.item(0).data;
                	memberElem['profile_name'] = node.childNodes.item((ie?1:3)).childNodes.item(0).data;
                	memberElem['country'] = node.childNodes.item((ie?2:5)).childNodes.item(0).data;
                	if (node.childNodes.item((ie?3:7)).childNodes.item(0)) memberElem['state'] = node.childNodes.item((ie?3:7)).childNodes.item(0).data;
                	else memberElem['state'] = '';
                	if (node.childNodes.item((ie?4:9)).childNodes.item(0)) memberElem['city'] = node.childNodes.item((ie?4:9)).childNodes.item(0).data;
                	else memberElem['city'] = '';
                	if (node.childNodes.item((ie?5:11)).childNodes.item(0))
                	{
                		splitted = node.childNodes.item((ie?5:11)).childNodes.item(0).data.split(".");
                		avatar = '';
                		for (i=0;i<splitted.length;i++)
                		{
                			if (i==0) dot = '';
                			else dot = '.';
                			if (i==splitted.length-1) avatar += '_thumb' + dot + splitted[i];
                			else avatar += splitted[i];
                		}
                		memberElem['avatar'] = 'photos/general/'+avatar;
                	}
                	else memberElem['avatar'] = 'photos/&no_pic..gif';
                	out.push(memberElem);
				}
			}
            window.wn_friends = out;
		}
	}

	xmlhttp.send(null);
}

function ajaxSearchStart(keyCode)
{
	/*not the ideal way to do this but I wasn't able to find how I can make function execute exactly after event has done its work*/
	//the user has pressed CTRL and we will fire later, when user preces V (if he will)
	if(keyCode!=17)
	{
		//this tells us that AJAX calls has successfully finished and window.wn_friends was populated
		if (window.wn_friends && window.wn_friends.length>0)
		{
			setTimeout("ajaxSearchDo();", 50);
		}
	}
}

function ajaxSearchDo()
{
	allFriends = window.wn_friends;
	searchString = document.getElementById('keywords').value;
	if (searchString)
	{
		showFriends = ajaxSearchFriends(allFriends, searchString);
		searchDiv = getSearchDiv();
		if (showFriends.length>0)
		{
			searchDiv.innerHTML = '';
			for(i=0;i<showFriends.length;i++)
			{
				if (i>0)
				{
					separatorDiv = document.createElement('div');
					separatorDiv.className = 'ajaxSearchSeparator';
					searchDiv.appendChild(separatorDiv);
				}
				friend = showFriends[i];
				friendDiv = getFriendDiv(friend);
            	searchDiv.appendChild(friendDiv);
			}
        	searchDiv.style.display = 'block';
		}
		else
		{
			searchDiv.style.display = 'none';
		}
	}
	else
	{
		//hide the box
		searchDiv = getSearchDiv();
		searchDiv.style.display = 'none';
	}
}

function getFriendDiv(friend, avatarWidth)
{
	if (!avatarWidth) avatarWidth = 25;
	//main box that contains everything zbout the current friend
	mainFriendDiv = document.createElement('div');
	mainFriendDiv.className = 'ajaxSearchFriendBox';
	mainFriendDiv.onmousedown = function()
	{
		base = document.getElementsByTagName('base');
		base = base[0].href;
		if(base)
		{
			if (base[base.length-1]!='/') base = base + '/';
			window.location = base + "index.php?page=view_profile&id="+friend['member_id'];
		}
	}
	//box that contains avatar
	avatarDiv = document.createElement('div');
	avatarDiv.className = 'ajaxSearchAvatarBox';
	//the avatar
	avatarImg = document.createElement('img');
	avatarImg.className = 'ajaxSearchAvatar';
	avatarImg.src = friend['avatar'];
	//detecting image size
	imageObj = new Image();
	imageObj.src = friend['avatar'];
    ratio = imageObj.width/avatarWidth;
	avatarImg.width = avatarWidth;
	avatarImg.height = imageObj.height/ratio;
	//profile name box
	profileNameDiv = document.createElement('div');
	profileNameDiv.className = 'ajaxSearchProfileNameBox';
	profile_name_start = friend['profile_name'].substring(0, friend['match_start']);
	profile_name_middle = friend['profile_name'].substring(friend['match_start'], friend['match_start']+friend['match_length']);
	profile_name_end = friend['profile_name'].substring(friend['match_start']+friend['match_length'], friend['profile_name'].length);
	profileNameDiv.innerHTML = profile_name_start + '<span class="ajaxSearchProfileMatchNameBox">' + profile_name_middle + '</span>' + profile_name_end;
	//location box
	locationDiv = document.createElement('div');
	locationDiv.className = 'ajaxSearchLocationBox';
	locationDiv.innerHTML = friend['city'] + (friend['state']?', '+friend['state']:'') + (friend['country']?', '+friend['country']:'');
	//good old fix for hasLayout and floated elements
	mainFriendDivClear = document.createElement('div');
	mainFriendDivClear.className = 'ajaxSearchFriendBoxClear';
	//now put all these stuff together
	avatarDiv.appendChild(avatarImg);
	mainFriendDiv.appendChild(avatarDiv);
	mainFriendDiv.appendChild(profileNameDiv);
	mainFriendDiv.appendChild(locationDiv);
	mainFriendDiv.appendChild(mainFriendDivClear);
    //return results
	return mainFriendDiv;
}

function ajaxSearchFriends(allFriends, searchString)
{
	reg = new RegExp("^"+searchString, "i");
	reg1 = new RegExp(" "+searchString, "i");
	foundFriends = new Array();
	for(i=0;i<allFriends.length;i++)
	{
		friend = allFriends[i];
		position = friend['profile_name'].search(reg);
		if (position==-1)
		{
			position = friend['profile_name'].search(reg1);
			if (position>-1) position = position + 1; //because the first character is space
		}

		if (position>-1)
		{
			friend['match_start'] = position;
			friend['match_length'] = searchString.length;
        	foundFriends.push(friend);
		}
	}

	return foundFriends;
}

function getSearchDiv()
{
	searchDiv = document.getElementById('ajaxSearchBox');
	if (!searchDiv)
	{
    	searchDiv = document.createElement('div');
    	searchDiv.id = 'ajaxSearchBox';
    	searchDiv.style.display = 'none';
    	searchDiv.className = 'ajaxSearchBox';
    	document.getElementById('keywords').parentNode.insertBefore(searchDiv, document.getElementById('keywords'));
	}

	return searchDiv;
}
