/***************************************************************************
 *                            Dolphin Web Community Software
 *                              -------------------
 *     begin                : Mon Mar 23 2006
 *     copyright            : (C) 2007 BoonEx Group
 *     website              : http://www.boonex.com
 *
 *
 *
 ****************************************************************************/

/***************************************************************************
 *
 *   This is a free software; you can modify it under the terms of BoonEx
 *   Product License Agreement published on BoonEx site at http://www.boonex.com/downloads/license.pdf
 *   You may not however distribute it for free or/and a fee.
 *   This notice may not be removed from the source code. You may not also remove any other visible
 *   reference and links to BoonEx Group as provided in source code.
 *
 ***************************************************************************/

/**
 * Checks/unchecks all tables
 *
 * @param   string   the form name
 * @param   boolean  whether to check or to uncheck the element
 *
 * @return  boolean  always true
 */

function setCheckboxes(the_form, do_check)
{
	var elts  = document.forms[the_form].getElementsByTagName('input');
    var elts_cnt  = elts.length;

    for ( i = 0; i < elts_cnt; i++)
    {
        elts[i].checked = do_check;
		if ( elts[i].type == "submit" )
			elts[i].disabled = !do_check;
    }
}

function UpdateSubmit(the_form) {
	var elts  = document.forms[the_form].getElementsByTagName('input');
	var elts_cnt  = elts.length;
	var bChecked = false;

	for ( i = 0; i < elts_cnt; i++) {
		if (elts[i].type == "checkbox" && elts[i].checked == true) {
			bChecked = true;
		}
		if ( elts[i].type == "submit" ) {
			elts[i].disabled = true;
		}
	}
	for ( i = 0; i < elts_cnt; i++) {
		if ( elts[i].type == "submit" ) {
			if (bChecked == true) {
				elts[i].disabled = false;
			} else {
				elts[i].disabled = true;
			}
		}
	}
}



function goto(){
window.location = "add_routes_tracks.php";
}

                                         
function setCheckbox(the_form)
{
    var elts      = document.forms[the_form].getElementsByTagName('input');
    var elts_cnt  = elts.length;

    var allUnchecked = true;

    for (var i = 0; i < elts_cnt; i++)
        if(elts[i].checked)
			allUnchecked = false;

    for (var i = 0; i < elts_cnt; i++)
        if( elts[i].type == "submit" )
			elts[i].disabled = allUnchecked;
}


var win = "width=500,height=600,left=100,top=100,copyhistory=no,directories=no,menubar=no,location=no,resizable=no,scrollbars=yes";
function get_gallery(id_prof)
{
   window.open("photos_gallery.php?ID="+id_prof,'gallery',win);
}

function launchTellFriend ()
{
    var win = "width=300,height=300,left=200,top=100,copyhistory=no,directories=no,menubar=no,location=no,resizable=no,scrollbars=no";
    window.open("tellfriend.php",'tellfriend',win);
    return false;
}

function launchTellFriendProfile ( sID )
{
    var win = "width=300,height=300,left=200,top=100,copyhistory=no,directories=no,menubar=no,location=no,resizable=no,scrollbars=no";
    window.open("tellfriend.php?ID="+sID,'tellfriendprofile',win);
    return false;
}

function BxShowBlock( id )
{

	var el;
	el = document.getElementById( id );

	if( el.style.display == 'none' )
	{
		el.style.display = 'block'
	}
	else
	{
		el.style.display = 'none'
	}

	return false;
}

function ShowShowHide ( show_name, show_name2, hide_name )
{
    if (hide_name) hide_name.style.display = 'none';
    if (show_name) show_name.style.display = 'inline';
    if (show_name2) show_name2.style.display = 'inline';
}

function ShowHideHide ( show_name, hide_name, hide_name2 )
{
    if (hide_name) hide_name.style.display = 'none';
    if (hide_name2) hide_name2.style.display = 'none';
    if (show_name) show_name.style.display = 'inline';
}

function charCounter(field,maxLength,countTarget)
{


	field = document.getElementById(field);
	countTarget = document.getElementById(countTarget);
	var inputLength=field.value.length;

	if(inputLength >= maxLength)
	{
		field.value=field.value.substring(0,maxLength);

	}
	countTarget.innerHTML=maxLength-field.value.length;


}



/**
 * change images onHover mouse action
 */
function show(FileName,jpg1Name)
{
	document.images[FileName].src = jpg1Name;
}

/**
 * set status of the browser window to 's'
 */
function ss(s)
{
	window.status = s;
	return true;
}

/**
 * set status of the browser window to empty
 */
function ce()
{
	window.status='';
}


/**
 * insert emotion item
 */
function emoticon( txtarea, text ) {

	text = ' ' + text + ' ';
	if (txtarea.createTextRange && txtarea.caretPos) {
		var caretPos = txtarea.caretPos;
		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text + ' ' : text;
		txtarea.focus();
	} else {
		txtarea.value  += text;
		txtarea.focus();
	}
}

function launchAddToIM (id)
{
    var win = "width=600,height=160,left=100,top=100,copyhistory=no,directories=no,menubar=no,location=no,resizable=no,scrollbars=yes";
    window.open("explanation.php?explain=imadd&ID="+id,'add_to_im',win);
    return false;
}

function docOpen(text)
{
	newWindow=window.open('','','toolbar=no,resizable=yes,scrollbars=yes,width=400,height=300');
	newWindow.document.open("text/html");
	newWindow.document.write(unescape(text));
	newWindow.document.close();
}

function get_data( container, url, siteUrl )
{
	if ( container )
	{
		var container = document.getElementById( container );
		container.innerHTML = "loading ... ";
	}

	var XMLHttpRequestObject = createXmlHttpObj();

	if( !XMLHttpRequestObject )
		return false;

	var data_source = siteUrl + 'xml/menu.php' + url + '&_t=' + Math.random();
	XMLHttpRequestObject.open( "GET", data_source );
	XMLHttpRequestObject.onreadystatechange = function()
	{
		if ( XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200 )
		{
			var xmlDocument = XMLHttpRequestObject.responseXML;
			delete XMLHttpRequestObject;
			XMLHttpRequestObject = null;
			
			names = xmlDocument.getElementsByTagName("name");
			links = xmlDocument.getElementsByTagName("link");
			
			list_sublinks(names, links);
		}
	}
	XMLHttpRequestObject.send( null );

	//container.innerHTML = '';

	function list_sublinks(names, links)
	{
		var loopIndex, name, link, maxIndex = names.length;

		container.innerHTML = '';
		for ( loopIndex = 0; loopIndex < maxIndex; loopIndex++ )
		{
			//if ( values[loopIndex].firstChild.nodeName=="name")
			name = names[loopIndex].firstChild.nodeValue;
			
			//if ( values[loopIndex].childNodes[1].nodeName=="link")
			link = links[loopIndex].firstChild.nodeValue;
			
			container.innerHTML += '<div class="innerSubmenuDiv"><a href="' + link + '">' + name + '</a></div>';
		}
	}
}


function createNamedElement( type, name )
{

    var element;

    try
    {
        element = document.createElement('<'+type+' name="'+name+'">');
    } catch (e) { }

    if (!element || !element.name) // Cool, this is not IE !!
    {
        element = document.createElement(type)
        element.name = name;
    }

    return element;
}

function display_node(node, siteUrl)
{

    var nn = document.getElementById( node );

	var sub_name = node.split('_')[1];
    if ( 'none' == nn.style.display )
    {
	nn.style.display='block';
	if ( '' == nn.innerHTML )
	    get_data( node, '?action=menu&ID=' + sub_name, siteUrl);
    }
    else
    {
		nn.style.display='none';
    }

}

function stripSlashes(str)
{
	return str.replace(/\\/g, '');
}

function createXmlHttpObj()
{
	if ( window.XMLHttpRequest )
		return new XMLHttpRequest();
	else if ( window.ActiveXObject )
		return new ActiveXObject("Microsoft.XMLHTTP");
	else
	{
		alert( 'Please upgrade your browser' );
		return false;
	}
}

function getHtmlData( elemID, url )
{
	var elem = document.getElementById( elemID );
	
	if( !elem || !url )
		return false;
	
	var url = url + '&r=' + Math.random();
	
	
	var oXMLHttpReq = createXmlHttpObj();
	
	if( !oXMLHttpReq )
		return false;
	
	elem.innerHTML = '<div class="loading"><img src="'+urlIconLoading+'"></div>';
	
	oXMLHttpReq.open( "GET", url );
	oXMLHttpReq.onreadystatechange = function()
	{
		if ( oXMLHttpReq.readyState == 4 && oXMLHttpReq.status == 200 )
		{
			sNewText = oXMLHttpReq.responseText;
			elem.innerHTML = sNewText;
			
			// parse javascripts and run them
			aScrMatches = sNewText.match(/<script[^>]*javascript[^>]*>([^<]*)<\/script>/ig);
			if( aScrMatches )
			{
				for( ind = 0; ind < aScrMatches.length; ind ++ )
				{
					sScr = aScrMatches[ind];
					iOffset = sScr.match(/<script[^>]*javascript[^>]*>/i)[0].length;
					sScript = sScr.substring( iOffset, sScr.length - 9 );
					
					eval( sScript );
				}
			}
		}
	}
	oXMLHttpReq.send( null );
}


/* 
	Show the Floating Description for any element.
	
	usage:
	<element
		onmouseover="showFloatDesc( 'your html description here...' );"
		onmousemove="moveFloatDesc( event );"
		onmouseout="hideFloatDesc();">
	
	Your document must contain in the root of body following content:
		<div id="FloatDesc" style="position:absolute;display:none;"></div>
	and specific stylesheet for it.
*/
function showFloatDesc( text )
{
	descDiv = document.getElementById( 'FloatDesc' );
	if ( descDiv )
	{
		descDiv.innerHTML = text;
		descDiv.style.display = 'block';
	}
}

function hideFloatDesc()
{
	descDiv = document.getElementById( 'FloatDesc' );
	if ( descDiv )
		descDiv.style.display = 'none';
}

function moveFloatDesc( ev )
{
	descDiv = document.getElementById( 'FloatDesc' );
	if ( descDiv )
	{
		showPos = getPositionData( descDiv, ev );
		descDiv.style.left = showPos['posX'] + 'px';
		descDiv.style.top = showPos['posY'] + 'px';
	}
}

/*
	Core of the Floating Description
*/
function getPositionData(obj, showEvent)
{
	if ( !showEvent )
		showEvent = window.event;
	
	var pos_X = 0, pos_Y = 0;
	if ( showEvent )
	{
		if ( typeof(showEvent.pageX) == 'number' )
		{
			pos_X = showEvent.pageX;
			pos_Y = showEvent.pageY;
		}
		else if ( typeof(showEvent.clientX) == 'number' )
		{
			pos_X = showEvent.clientX; pos_Y = showEvent.clientY;
			if ( document.body && 
				( document.body.scrollTop || document.body.scrollLeft ) && 
				!( window.opera || window.debug || navigator.vendor == 'KDE' ) )
			{
				pos_X += document.body.scrollLeft;
				pos_Y += document.body.scrollTop;
			}
			else if ( document.documentElement &&
				( document.documentElement.scrollTop ||
				document.documentElement.scrollLeft ) &&
				!( window.opera || window.debug || navigator.vendor == 'KDE' ) )
			{
				pos_X += document.documentElement.scrollLeft;
				pos_Y += document.documentElement.scrollTop;
			}
		}
	}
	
	var scroll_X = 0, scroll_Y = 0;
	if ( document.body &&
		( document.body.scrollTop || document.body.scrollLeft ) &&
		!( window.debug || navigator.vendor == 'KDE' ) )
	{
		scroll_X = document.body.scrollLeft;
		scroll_Y = document.body.scrollTop;
	}
	else if ( document.documentElement &&
		( document.documentElement.scrollTop ||
		document.documentElement.scrollLeft ) &&
		!( window.debug || navigator.vendor == 'KDE' ) )
	{
		scroll_X = document.documentElement.scrollLeft;
		scroll_Y = document.documentElement.scrollTop;
	}
	
	var win_size_X = 0, win_size_Y = 0;
	if (window.innerWidth && window.innerHeight)
	{
		win_size_X = window.innerWidth;
		win_size_Y = window.innerHeight;
	}
	else if ( document.documentElement &&
		document.documentElement.clientWidth &&
		document.documentElement.clientHeight )
	{
		win_size_X = document.documentElement.clientWidth;
		win_size_Y = document.documentElement.clientHeight;
	}
	else if (document.body && document.body.clientWidth && document.body.clientHeight)
	{
		win_size_X = document.body.clientWidth;
		win_size_Y = document.body.clientHeight;
	}
	
	pos_X += 15;
	pos_Y += 20;
	
	if (obj.offsetWidth && obj.offsetHeight)
	{
		if (pos_X - scroll_X + obj.offsetWidth + 5 > win_size_X)
			pos_X -= (obj.offsetWidth + 25);
		if (pos_Y - scroll_Y + obj.offsetHeight + 5 > win_size_Y)
			pos_Y -= (obj.offsetHeight + 20);
	}
	
	var res = new Array;
	res['posX'] = pos_X;
	res['posY'] = pos_Y;
	res['scrollX'] = scroll_X;
	res['scrollY'] = scroll_Y;
	res['winSizeX'] = win_size_X;
	res['winSizeY'] = win_size_Y;
	
	return res;
}

function addBookmark( title, url )
{
	if (title == undefined)
		title = document.title;

	if (url == undefined)
		url = top.location.href;
		
	if (window.sidebar) // firefox
		window.sidebar.addPanel(title, url, '');
	else if(window.opera && window.print) // opera
	{
		var elem = document.createElement('a');
		elem.setAttribute('href',url);
		elem.setAttribute('title',title);
		elem.setAttribute('rel','sidebar');
		elem.click();
	} 
	else if(document.all) // ie
		window.external.AddFavorite(url, title);
	else if (navigator.appName=="Netscape") //Netscape
		alert( 'To bookmark this site press "Ctrl+D".' );
	else
		alert( 'Your browser doesn\'t support this feature' );
}

newID = 2;
 
function AddFilesFields() {
	var el;
	el = document.getElementById( 'browse_file_div' );
	if (el.childNodes.length > 10) {
		alert('5 files maximum');
		return;
	}
	newEl = document.createElement( 'INPUT' );
	newEl.type = 'file';
	newEl.name = 'userfile[]';
	//newEl.id   = 'file_' + newID;
	el.appendChild( newEl );
	newElbr = document.createElement( 'BR' );
	el.appendChild( newElbr );
	newID ++;
}

function changeBigPicTo(newBigImageName, newBigImageHref) {
	var el;
	el = document.getElementById('AdvBigImg');
	el.style.backgroundImage = 'url(' + newBigImageName + ')';
	el = document.getElementById('AdvBigImgFullSize');
	el.href = newBigImageHref;
}

function moveScrollRightAuto( el_id, b ) {
	if (b)
		scrollTimerId = setInterval ("moveScrollRight('"+el_id+"')", 100);
	else
		clearInterval (scrollTimerId);
}

function moveScrollLeftAuto( el_id, b ) {
	if (b)
		scrollTimerId = setInterval ("moveScrollLeft('"+el_id+"')", 100);
	else
		clearInterval (scrollTimerId);
}

function moveScrollRight( el_id ) {
	var step = 5;
	var e = document.getElementById( el_id );
	var left  = e.style.left ? parseInt( e.style.left ) : 0;

	minLeft = e.parentNode.clientWidth - parseInt( e.clientWidth );

	if ( (left-step) > minLeft ) {
		e.style.left = left - step + "px";
	}
	else {
		e.style.left = minLeft + "px";
		moveScrollRightAuto ( el_id, false);
	}
}

function moveScrollLeft( el_id ) {
	var step = 5;
	var e = document.getElementById( el_id );
	var left = parseInt(e.style.left ? e.style.left : 0);

	if (left + step < 0 ) {
		e.style.left = left + step + "px";
	}
	else {
		e.style.left = "0px";
		moveScrollLeftAuto (false);
	}
}

function addEvent( obj, evt, func )
{
	if( !obj || !evt || !func )
		return false;
	
	if( obj.addEventListener )
		obj.addEventListener( evt, func, false );
	else if( obj.attachEvent )
		obj.attachEvent( 'on' + evt, func );
}

function showHiddenMenu( id )
{
	setTimeout( 'if( holdHiddenMenu == ' + id + ' ){ var _el = document.getElementById( \'hiddenMenu_' + id + '\' ); if( _el ){ hideHiddenMenu( currentTopItem ); _el.style.display = \'block\'; } }', 100 );
}

if( typeof( holdHiddenMenu ) == 'undefined' )
	holdHiddenMenu = 0;

function hideHiddenMenu( id )
{
	setTimeout( 'if( holdHiddenMenu != ' + id + ' ){ var _el = document.getElementById( \'hiddenMenu_' + id + '\' ); if( _el ){ showHiddenMenu( currentTopItem ); _el.style.display = \'none\'; } }', 100 );
}

function checkAll( formName, _pref, doCheck ) {
	_form = document.forms[formName];
	
	if( !_form )
		return false;
	
	for( ind = 0; ind < _form.length; ind ++ ) {
		_elem = _form[ind];

		if( _elem.type != 'checkbox' )
			continue;

		if( _elem.name.substr( 0, _pref.length ) != _pref )
			continue;

		_elem.checked = doCheck;
	}
}

function emailCheck( str )
{


 if (str.search( /^[a-z0-9_\-]+(\.[_a-z0-9\-]+)*@([_a-z0-9\-]+\.)+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel)$/i ) == -1 )
 	return false;
 else
 	return true;
}

function getBoonexId( formFrom, formTo )
{
	if( !formFrom || !formTo )
		return false;
	
	ID = formFrom.ID;
	Password = formFrom.Password;
	
	if( !ID || !Password )
		return false;
	
	var oXMLHttpReq = createXmlHttpObj();
	
	if( !oXMLHttpReq )
		return false;
	
	if( !ID.value.length )
	{
		alert( 'Please enter BoonEx ID' );
		ID.focus();
		return false;
	}

	if( !Password.value.length )
	{
		alert( 'Please enter Password' );
		Password.focus();
		return false;
	}
	
	formFrom.Submit.disabled = true;
	formFrom.Submit.value = 'Wait...';
	
	sUrl = 'get_boonex_id.php?ID=' + encodeURIComponent(ID.value) + '&Password=' + encodeURIComponent(Password.value) + '&r=' + Math.random();
	
	oXMLHttpReq.open( "GET", sUrl );
	oXMLHttpReq.onreadystatechange = function()
	{
		if ( oXMLHttpReq.readyState == 4 && oXMLHttpReq.status == 200 )
		{
			//alert( oXMLHttpReq.responseText );
			oXML = oXMLHttpReq.responseXML;
			
			if( !oXML.getElementsByTagName( 'ID' ).length )
			{
				alert( 'Authorization failed. Try again.' );
				return false;
			}
			
			aFields = new Array();
			aFields['Username'] = 'NickName';
			aFields['Email']    = 'Email';
			aFields['Password'] = 'Password,Password1,Password2';
			aFields['Realname'] = 'Realname';
			aFields['DateOfBirth'] = 'DateOfBirth';
			aFields['Sex']      = 'Sex';
			aFields['Country']  = 'Country';
			aFields['City']     = 'City';
			aFields['ZIP']      = 'zip';
			aFields['Headline'] = 'Headline';
			aFields['DescriptionMe'] = 'DescriptionMe';
			aFields['tags']     = 'Tags';
			
			for( fieldFrom in aFields )
			{
				if( !oXML.getElementsByTagName( fieldFrom ).length )
					continue;
				
				eFieldFrom = oXML.getElementsByTagName( fieldFrom )[0];
				sValue = eFieldFrom.firstChild.data;
				
				aFieldsTo = aFields[fieldFrom].split( ',' );
				
				for( i in aFieldsTo )
				{
					fieldTo = aFieldsTo[i];
					if( formTo[fieldTo] )
					{
						eFieldTo = formTo[fieldTo];
						
						switch( eFieldTo.type )
						{
							case 'text':
							case 'textarea':
							case 'password':
							case 'select-one':
								eFieldTo.value = sValue;
								break;
							default:
								if( typeof eFieldTo == 'object' ) //radio
									for( n = 0; n < eFieldTo.length; n++ )
										if( eFieldTo[n].value == sValue )
											eFieldTo[n].checked = true;
						}
					}
					else if( formTo[fieldTo + '_day'] && formTo[fieldTo + '_month'] && formTo[fieldTo + '_year'] ) //date
					{
						aDate = sValue.split( '-' );
						
						if( aDate[2].substr( 0, 1 ) == '0' ) //drop leading zero
							aDate[2] = aDate[2].substr( 1, 1 );
						
						formTo[fieldTo + '_year'].value  = aDate[0];
						formTo[fieldTo + '_month'].value = aDate[1];
						formTo[fieldTo + '_day'].value   = aDate[2];
					}
				}
			}
		}
	}
	oXMLHttpReq.send( null );

	formFrom.Submit.disabled = false;
	formFrom.Submit.value = 'Import';
}



// Title: Tigra Calendar
// URL: http://www.softcomplex.com/products/tigra_calendar/
// Version: 3.3 (American date format)
// Date: 09/01/2005 (mm/dd/yyyy)
// Note: Permission given to use this script in ANY kind of applications if
//    header lines are left unchanged.
// Note: Script consists of two files: calendar?.js and calendar.html

// if two digit year input dates after this year considered 20 century.
var NUM_CENTYEAR = 30;
// is time input control required by default
var BUL_TIMECOMPONENT = false;
// are year scrolling buttons required by default
var BUL_YEARSCROLL = true;

var calendars = [];
var RE_NUM = /^\-?\d+$/;

function calendar2(obj_target) {

	// assigning methods
	this.gen_date = cal_gen_date2;
	this.gen_time = cal_gen_time2;
	this.gen_tsmp = cal_gen_tsmp2;
	this.prs_date = cal_prs_date2;
	this.prs_time = cal_prs_time2;
	this.prs_tsmp = cal_prs_tsmp2;
	this.popup    = cal_popup2;

	// validate input parameters
	if (!obj_target)
		return cal_error("Error calling the calendar: no target control specified");
	if (obj_target.value == null)
		return cal_error("Error calling the calendar: parameter specified is not valid target control");
	this.target = obj_target;
	this.time_comp = BUL_TIMECOMPONENT;
	this.year_scroll = BUL_YEARSCROLL;
	
	// register in global collections
	this.id = calendars.length;
	calendars[this.id] = this;
}

function cal_popup2 (str_datetime) {
	if (str_datetime) {
		this.dt_current = this.prs_tsmp(str_datetime);
	}
	else {
		this.dt_current = this.prs_tsmp(this.target.value);
		this.dt_selected = this.dt_current;
	}
	if (!this.dt_current) return;

	var obj_calwindow = window.open(
		'calendar.html?datetime=' + this.dt_current.valueOf()+ '&id=' + this.id,
		'Calendar', 'width=200,height='+(this.time_comp ? 215 : 190)+
		',status=no,resizable=no,top=200,left=200,dependent=yes,alwaysRaised=yes'
	);
	obj_calwindow.opener = window;
	obj_calwindow.focus();
}

// timestamp generating function
function cal_gen_tsmp2 (dt_datetime) {
	return(this.gen_date(dt_datetime) + ' ' + this.gen_time(dt_datetime));
}

// date generating function
function cal_gen_date2 (dt_datetime) {
	return (
		
		(dt_datetime.getDate() < 10 ? '0' : '') + dt_datetime.getDate() + "/"
		+ (dt_datetime.getMonth() < 9 ? '0' : '') + (dt_datetime.getMonth() + 1) + "/"
		+ dt_datetime.getFullYear()
	);
}
// time generating function
function cal_gen_time2 (dt_datetime) {
	return (
		(dt_datetime.getHours() < 10 ? '0' : '') + dt_datetime.getHours() + ":"
		+ (dt_datetime.getMinutes() < 10 ? '0' : '') + (dt_datetime.getMinutes()) + ":"
		+ (dt_datetime.getSeconds() < 10 ? '0' : '') + (dt_datetime.getSeconds())
	);
}

// timestamp parsing function
function cal_prs_tsmp2 (str_datetime) {
	// if no parameter specified return current timestamp
	if (!str_datetime)
		return (new Date());

	// if positive integer treat as milliseconds from epoch
	if (RE_NUM.exec(str_datetime))
		return new Date(str_datetime);
		
	// else treat as date in string format
	var arr_datetime = str_datetime.split(' ');
	return this.prs_time(arr_datetime[1], this.prs_date(arr_datetime[0]));
}

// date parsing function
function cal_prs_date2 (str_date) {

	var arr_date = str_date.split('/');

	if (arr_date.length != 3) return cal_error ("Invalid date format: '" + str_date + "'.\nFormat accepted is dd-mm-yyyy.");
	if (!arr_date[0]) return cal_error ("Invalid date format: '" + str_date + "'.\nNo day of month value can be found.");
	if (!RE_NUM.exec(arr_date[0])) return cal_error ("Invalid day of month value: '" + arr_date[0] + "'.\nAllowed values are unsigned integers.");
	if (!arr_date[1]) return cal_error ("Invalid date format: '" + str_date + "'.\nNo month value can be found.");
	if (!RE_NUM.exec(arr_date[1])) return cal_error ("Invalid month value: '" + arr_date[1] + "'.\nAllowed values are unsigned integers.");
	if (!arr_date[2]) return cal_error ("Invalid date format: '" + str_date + "'.\nNo year value can be found.");
	if (!RE_NUM.exec(arr_date[2])) return cal_error ("Invalid year value: '" + arr_date[2] + "'.\nAllowed values are unsigned integers.");

	var dt_date = new Date();
	dt_date.setDate(1);

	if (arr_date[1] < 1 || arr_date[1] > 12) return cal_error ("Invalid month value: '" + arr_date[1] + "'.\nAllowed range is 01-12.");
	dt_date.setMonth(arr_date[1]-1);
	 
	if (arr_date[2] < 100) arr_date[2] = Number(arr_date[2]) + (arr_date[2] < NUM_CENTYEAR ? 2000 : 1900);
	dt_date.setFullYear(arr_date[2]);

	var dt_numdays = new Date(arr_date[2], arr_date[1], 0);
	dt_date.setDate(arr_date[0]);
	if (dt_date.getMonth() != (arr_date[1]-1)) return cal_error ("Invalid day of month value: '" + arr_date[0] + "'.\nAllowed range is 01-"+dt_numdays.getDate()+".");

	return (dt_date)
}

// time parsing function
function cal_prs_time2 (str_time, dt_date) {

	if (!dt_date) return null;
	var arr_time = String(str_time ? str_time : '').split(':');

	if (!arr_time[0]) dt_date.setHours(0);
	else if (RE_NUM.exec(arr_time[0])) 
		if (arr_time[0] < 24) dt_date.setHours(arr_time[0]);
		else return cal_error ("Invalid hours value: '" + arr_time[0] + "'.\nAllowed range is 00-23.");
	else return cal_error ("Invalid hours value: '" + arr_time[0] + "'.\nAllowed values are unsigned integers.");
	
	if (!arr_time[1]) dt_date.setMinutes(0);
	else if (RE_NUM.exec(arr_time[1]))
		if (arr_time[1] < 60) dt_date.setMinutes(arr_time[1]);
		else return cal_error ("Invalid minutes value: '" + arr_time[1] + "'.\nAllowed range is 00-59.");
	else return cal_error ("Invalid minutes value: '" + arr_time[1] + "'.\nAllowed values are unsigned integers.");

	if (!arr_time[2]) dt_date.setSeconds(0);
	else if (RE_NUM.exec(arr_time[2]))
		if (arr_time[2] < 60) dt_date.setSeconds(arr_time[2]);
		else return cal_error ("Invalid seconds value: '" + arr_time[2] + "'.\nAllowed range is 00-59.");
	else return cal_error ("Invalid seconds value: '" + arr_time[2] + "'.\nAllowed values are unsigned integers.");

	dt_date.setMilliseconds(0);
	return dt_date;
}

function cal_error (str_message) {
	alert (str_message);
	return null;
}

function mypopup(url)
 {alert(url)
   mywindow = window.open (url,"mywindow","location=1,status=1,scrollbars=1,width=850,height=500");
   mywindow.moveTo(0,0);
 } 

function mypopup1(url)
 {
   mywindow = window.open (url,"mywindow","location=1,status=1,scrollbars=1,width=350,height=250");
   mywindow.moveTo(0,0);
 } 
function mypopup2(url)
 {
   mywindow = window.open (url,"mywindow","location=1,status=1,scrollbars=1,width=500,height=450");
  // mywindow.moveTo(0,0);
 } 


function loadsubcat()
{
window.activity_form.submit();
}




/* Simple AJAX Code-Kit (SACK) v1.6.1 */
/* ©2005 Gregory Wild-Smith */
/* www.twilightuniverse.com */
/* Software licenced under a modified X11 licence,
   see documentation or authors website for more details */

function sack(file) {
	this.xmlhttp = null;

	this.resetData = function() {
		this.method = "POST";
  		this.queryStringSeparator = "?";
		this.argumentSeparator = "&";
		this.URLString = "";
		this.encodeURIString = true;
  		this.execute = false;
  		this.element = null;
		this.elementObj = null;
		this.requestFile = file;
		this.vars = new Object();
		this.responseStatus = new Array(2);
  	};

	this.resetFunctions = function() {
  		this.onLoading = function() { };
  		this.onLoaded = function() { };
  		this.onInteractive = function() { };
  		this.onCompletion = function() { };
  		this.onError = function() { };
		this.onFail = function() { };
	};

	this.reset = function() {
		this.resetFunctions();
		this.resetData();
	};

	this.createAJAX = function() {
		try {
			this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e1) {
			try {
				this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e2) {
				this.xmlhttp = null;
			}
		}

		if (! this.xmlhttp) {
			if (typeof XMLHttpRequest != "undefined") {
				this.xmlhttp = new XMLHttpRequest();
			} else {
				this.failed = true;
			}
		}
	};

	this.setVar = function(name, value){
		this.vars[name] = Array(value, false);
	};

	this.encVar = function(name, value, returnvars) {
		if (true == returnvars) {
			return Array(encodeURIComponent(name), encodeURIComponent(value));
		} else {
			this.vars[encodeURIComponent(name)] = Array(encodeURIComponent(value), true);
		}
	}

	this.processURLString = function(string, encode) {
		encoded = encodeURIComponent(this.argumentSeparator);
		regexp = new RegExp(this.argumentSeparator + "|" + encoded);
		varArray = string.split(regexp);
		for (i = 0; i < varArray.length; i++){
			urlVars = varArray[i].split("=");
			if (true == encode){
				this.encVar(urlVars[0], urlVars[1]);
			} else {
				this.setVar(urlVars[0], urlVars[1]);
			}
		}
	}

	this.createURLString = function(urlstring) {
		if (this.encodeURIString && this.URLString.length) {
			this.processURLString(this.URLString, true);
		}

		if (urlstring) {
			if (this.URLString.length) {
				this.URLString += this.argumentSeparator + urlstring;
			} else {
				this.URLString = urlstring;
			}
		}

		// prevents caching of URLString
		this.setVar("rndval", new Date().getTime());

		urlstringtemp = new Array();
		for (key in this.vars) {
			if (false == this.vars[key][1] && true == this.encodeURIString) {
				encoded = this.encVar(key, this.vars[key][0], true);
				delete this.vars[key];
				this.vars[encoded[0]] = Array(encoded[1], true);
				key = encoded[0];
			}

			urlstringtemp[urlstringtemp.length] = key + "=" + this.vars[key][0];
		}
		if (urlstring){
			this.URLString += this.argumentSeparator + urlstringtemp.join(this.argumentSeparator);
		} else {
			this.URLString += urlstringtemp.join(this.argumentSeparator);
		}
	}

	this.runResponse = function() {
		eval(this.response);
	}

	this.runAJAX = function(urlstring) {
		if (this.failed) {
			this.onFail();
		} else {
			this.createURLString(urlstring);
			if (this.element) {
				this.elementObj = document.getElementById(this.element);
			}
			if (this.xmlhttp) {
				var self = this;
				if (this.method == "GET") {
					totalurlstring = this.requestFile + this.queryStringSeparator + this.URLString;
					this.xmlhttp.open(this.method, totalurlstring, true);
				} else {
					this.xmlhttp.open(this.method, this.requestFile, true);
					try {
						this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
					} catch (e) { }
				}

				this.xmlhttp.onreadystatechange = function() {
					switch (self.xmlhttp.readyState) {
						case 1:
							self.onLoading();
							break;
						case 2:
							self.onLoaded();
							break;
						case 3:
							self.onInteractive();
							break;
						case 4:
							self.response = self.xmlhttp.responseText;
							self.responseXML = self.xmlhttp.responseXML;
							self.responseStatus[0] = self.xmlhttp.status;
							self.responseStatus[1] = self.xmlhttp.statusText;

							if (self.execute) {
								self.runResponse();
							}

							if (self.elementObj) {
								elemNodeName = self.elementObj.nodeName;
								elemNodeName.toLowerCase();
								if (elemNodeName == "input"
								|| elemNodeName == "select"
								|| elemNodeName == "option"
								|| elemNodeName == "textarea") {
									self.elementObj.value = self.response;
								} else {
									self.elementObj.innerHTML = self.response;
								}
							}
							if (self.responseStatus[0] == "200") {
								self.onCompletion();
							} else {
								self.onError();
							}

							self.URLString = "";
							break;
					}
				};

				this.xmlhttp.send(this.URLString);
			}
		}
	};

	this.reset();
	this.createAJAX();
}








var ajax = new sack();

function getCityList(sel,val)
{  
    
	var countryCode = sel.options[sel.selectedIndex].value;
	//document.getElementById('activity_main').options.length = 0;
	document.getElementById('activity_sub').options.length = 0;	
	//alert(countryCode);// Empty city select box
	if(countryCode.length>0){
		ajax.requestFile = 'getCities.php?countryCode='+countryCode;	// Specifying which file to get
		ajax.onCompletion = createCities;	// Specify function that will be executed after file has been found
		ajax.runAJAX();		// Execute AJAX function
	}
}

function createCities()
{
//alert("asd");
	var obj = document.getElementById('activity_sub');
	//alert("obj"+obj);
	//var obj1 = document.getElementById('pur_jobs');
	//alert("hai"+obj1);
	eval(ajax.response);	// Executing the response from Ajax as Javascript code	
}


function  CaloriesBurnt(){

var obj1 = document.getElementById('activity_main')

if(obj1.value==''){
alert("Please Select Activity  !!");
return false;
}

var obj3 = document.getElementById('activity_sub')
if(obj3.value==''){
alert("Please Select Exercise Done !!");
return false;
}

var obj2 = document.getElementById('time_spent')
if(obj2.value==''){
alert("Please Enter Time spent !!");
document.activity_form.time_spent.focus();
return false;
}

var obj4 = document.getElementById('weight')

if(obj4.value==''){
alert("Please Enter Weight in Health Track Profile!!");
//document.activity_form.weight.focus();
return false;
}
if(obj4.value==0){
alert("Please Enter Weight in Health Track Profile!!");
//document.activity_form.weight.focus();
return false;
}

mets     = document.activity_form.mets.value
weight   = document.activity_form.weight.value
duration = document.activity_form.time_spent.value
calori   = ((mets * 3.5 * weight)/200) * duration 

document.activity_form.calories_burnt.value = calori
}


function metsvalue(sel)
{

var val = sel.options[sel.selectedIndex].value;

ajax.requestFile = 'getCities.php?val='+val;	// Specifying which file to get
		ajax.onCompletion = getsubmets;	// Specify function that will be executed after file has been found
		ajax.runAJAX();		// Execute AJAX function

}



function getsubmets()
{

var obj = document.getElementById('mets');

eval(ajax.response);
val = ajax.response
document.activity_form.mets.value = val


}
function gotohealthtrack(){

 window.location = "healthtrack_profile.php";
}

function show()
	{
		var listenersArrow = document.getElementById("test");  
		
              if(listenersArrow.style.display == 'none'){
	       listenersArrow.style.display = "block"; }else{
               listenersArrow.style.display = "none"; }
			
	}	


function  previewShow(sel){
 val = sel.value;
		/*var listenersArrow = document.getElementById("preview");  
		
              if(listenersArrow.style.display == 'none'){
	       listenersArrow.style.display = "block"; }else{
               listenersArrow.style.display = "none"; }*/
			   
		ajax.requestFile = 'getCities.php?poke='+val;	// Specifying which file to get
		ajax.onCompletion = getpreviewShow;	// Specify function that will be executed after file has been found
		ajax.runAJAX();		// Execute AJAX function
	   
		 
}
function getpreviewShow()
{

//var obj = document.getElementById('pokepreview');
//eval(ajax.response);
val = ajax.response
 
var label =  document.getElementById("pokepreview");
label.innerHTML =val;
  

}

function show_add()
	{
		var listenersArrow = document.getElementById("show_add");  
		
              if(listenersArrow.style.display == 'none'){
	       listenersArrow.style.display = "block"; }else{
               listenersArrow.style.display = "none"; }
			
	}	


function popup3(mylink, windowname)
{
if (! window.focus)return true;
var href;
if (typeof(mylink) == 'string')
   href=mylink;
else
   href=mylink.href;
window.open(href, windowname, 'width=900,height=600,scrollbars=yes');
return false;
}


function popup4(mylink, windowname)
{
if (! window.focus)return true;
var href;
if (typeof(mylink) == 'string')
   href=mylink;
else
   href=mylink.href;
window.open(href, windowname, 'width=500,height=300,scrollbars=yes');
return false;
}

function add(f){
alert(f.name);
forms = f.name
window.forms.submit()

}


function map(){
	
	for (var i=0; i < document.list_routes.radiobutton.length; i++)
   {
   if (document.list_routes.radiobutton[i].checked)
      {
      var rad_val = document.list_routes.radiobutton[i].value;
      }
   }

if (document.list_routes.radiobutton.checked) {

   if(typeof(rad_val)=="undefined"){
   var rad_val = document.list_routes.radiobutton.value
   }
}else{

if(typeof(rad_val)=="undefined"){
	alert("Please Select a Record !");
	return false;
}
}


	window.open("map_drow.php?edit_id="+rad_val,"windowname", "width=850,height=550,scrollbars=yes");
    
}


function videos(){
	
	 
	for (var i=0; i < document.list_routes.radiobutton.length; i++)
   {
   if (document.list_routes.radiobutton[i].checked)
      {
      var rad_val = document.list_routes.radiobutton[i].value;
      }
   }
if (document.list_routes.radiobutton.checked) {
   if(typeof(rad_val)=="undefined"){
   var rad_val = document.list_routes.radiobutton.value
   }
}else{

if(typeof(rad_val)=="undefined"){
	alert("Please Select a Record !");
	return false;
}
}

	//window.open("tracks_video.php?edit_id="+rad_val,"windowname", "width=850,height=550,scrollbars=yes");
	window.location = "tracks_video.php?edit_id="+rad_val 
    
}
 
function edit(){
	
	for (var i=0; i < document.list_routes.radiobutton.length; i++)
   {
      if (document.list_routes.radiobutton[i].checked)
      {
      var rad_val = document.list_routes.radiobutton[i].value;
      }
   }

if (document.list_routes.radiobutton.checked) {
   if(typeof(rad_val)=="undefined"){
   var rad_val = document.list_routes.radiobutton.value
   }
}else{

if(typeof(rad_val)=="undefined"){
	alert("Please Select a Record !");
	return false;
}
}


	//window.open("edit_routes_tracks.php?edit_id="+rad_val,"windowname", "width=850,height=550,scrollbars=yes");
	window.location = "edit_routes_tracks.php?edit_id="+rad_val 
    
}
  
function viewmap(){
	
	for (var i=0; i < document.list_routes.radiobutton.length; i++)
   {
   if (document.list_routes.radiobutton[i].checked)
      {
      var rad_val = document.list_routes.radiobutton[i].value;
      }
   }

if (document.list_routes.radiobutton.checked) {
   if(typeof(rad_val)=="undefined"){
   var rad_val = document.list_routes.radiobutton.value
   }
}else{

if(typeof(rad_val)=="undefined"){
	alert("Please Select a Record !");
	return false;
}
}

	window.open("view_routs.php?edit_id="+rad_val,"windowname", "width=850,height=550,scrollbars=yes");
    
}


function favorite(){
	
	for (var i=0; i < document.list_routes.radiobutton.length; i++)
   {
   if (document.list_routes.radiobutton[i].checked)
      {
      var rad_val = document.list_routes.radiobutton[i].value;
      }
   }

if (document.list_routes.radiobutton.checked) {
   if(typeof(rad_val)=="undefined"){
   var rad_val = document.list_routes.radiobutton.value
   }
}else{

if(typeof(rad_val)=="undefined"){
	alert("Please Select a Record !");
	return false;
}
}


	window.open("addtofavorite.php?edit_id="+rad_val,"windowname", "width=280,height=120,scrollbars=yes");
    
}
function delete_map(){
	
	for (var i=0; i < document.list_routes.radiobutton.length; i++)
   {
   if (document.list_routes.radiobutton[i].checked)
      {
      var rad_val = document.list_routes.radiobutton[i].value;
      }
   }

if (document.list_routes.radiobutton.checked) {
   if(typeof(rad_val)=="undefined"){
   var rad_val = document.list_routes.radiobutton.value
   }
}else{

if(typeof(rad_val)=="undefined"){
	alert("Please Select a Record !");
	return false;
}
}

var an =  confirm('Do You Really Want To Delete This Record ?');

if(an)
    window.location = "routes_tracks.php?delete_id="+rad_val 
}

function delete_autograph(){
	

var an =  confirm('Do You Really Want To Delete This Record ?');

if(an)
    window.location = "routes_tracks.php?delete_id="+rad_val 
}


function check_addmap(){

if(document.addroutes.routs_name.value=='')
{
			alert("Please Enter Routes/Tracks Name!");
			document.addroutes.routs_name.focus();
			return false;
}
	
}

function fckeditor(name)
{
	window.open("fckeditor.php?name="+name,'fckeditor',"menubar=1,resizable=0,width=720,height=450,top=100,left=100");
}
function taketour()
{
	window.open("taketour.php",'TakeTheTour',"menubar=0,resizable=0,width=900,height=520,top=0,left=0");

}
function taketour1()
{
	window.open("taketour1.php",'TakeTheTour',"menubar=0,resizable=0,width=900,height=600,top=0,left=0");

}

function textCounter(field,cntfield,maxlimit) {
if (field.value.length > maxlimit) // if too long...trim it!
field.value = field.value.substring(0, maxlimit);
// otherwise, update 'characters left' counter
else
cntfield.value = maxlimit - field.value.length;
}

function checkAll1(theForm, cName, allNo_stat) {

var n=theForm.elements.length;
for (var i=0;i<n;i++){
if (theForm.elements[i].className.indexOf(cName) !=-1){
if (allNo_stat.checked) {
theForm.elements[i].checked = true;
} else {
theForm.elements[i].checked = false;
}
}
}
}
