/*
This lib for cross browser handling taken from http://www.alistapart.com/articles/popuplinks
extended version is at http://v2studio.com/k/code/lib/


ARRAY EXTENSIONS

push(item [,...,item])
    Mimics standard push for IE5, which doesn't implement it.


find(value [, start])
    searches array for value starting at start (if start is not provided,
    searches from the beginning). returns value index if found, otherwise
    returns -1;


has(value)
    returns true if value is found in array, otherwise false;


FUNCTIONAL

map(list, func)
    traverses list, applying func to list, returning an array of values returned
    by func

    if func is not provided, the array item is returned itself. this is an easy
    way to transform fake arrays (e.g. the arguments object of a function or
    nodeList objects) into real javascript arrays.

    map also provides a safe way for traversing only an array's indexed items,
    ignoring its other properties. (as opposed to how for-in works)

    this is a simplified version of python's map. parameter order is different,
    only a single list (array) is accepted, and the parameters passed to func
    are different:
    func takes the current item, then, optionally, the current index and a
    reference to the list (so that func can modify list)


filter(list, func)
    returns an array of values in list for which func is true

    if func is not specified the values are evaluated themselves, that is,
    filter will return an array of the values in list which evaluate to true

    this is a similar to python's filter, but parameter order is inverted


DOM

getElem(elem)
    returns an element in document. elem can be the id of such element or the
    element itself (in which case the function does nothing, merely returning
    it)

    this function is useful to enable other functions to take either an    element
    directly or an element id as parameter.

    if elem is string and there's no element with such id, it throws an error.
    if elem is an object but not an Element, it's returned anyway


hasClass(elem, className)
    Checks the class list of element elem or element of id elem for className,
    if found, returns true, otherwise false.

    The tested element can have multiple space-separated classes. className must
    be a single class (i.e. can't be a list).


getElementsByClass(className [, tagName [, parentNode]])
    Returns elements having class className, optionally being a tag tagName
    (otherwise any tag), optionally being a descendant of parentNode (otherwise
    the whole document is searched)


DOM EVENTS

listen(event,elem,func)
    x-browser function to add event listeners

    listens for event on elem with func
    event is string denoting the event name without the on- prefix. e.g. 'click'
    elem is either the element object or the element's id
    func is the function to call when the event is triggered

    in IE, func is wrapped and this wrapper passes in a W3CDOM_Event (a faux
    simplified Event object)


mlisten(event, elem_list, func)
    same as listen but takes an element list (a NodeList, Array, etc) instead of
    an element.


W3CDOM_Event(currentTarget)
    is a faux Event constructor. it should be passed in IE when a function
    expects a real Event object. For now it only implements the currentTarget
    property and the preventDefault method.

    The currentTarget value must be passed as a paremeter at the moment    of
    construction.


MISC CLEANING-AFTER-MICROSOFT STUFF

isUndefined(v)
    returns true if [v] is not defined, false otherwise

    IE 5.0 does not support the undefined keyword, so we cannot do a direct
    comparison such as v===undefined.
*/

// ARRAY EXTENSIONS

if (!Array.prototype.push) Array.prototype.push = function() {
    for (var i=0; i<arguments.length; i++) this[this.length] = arguments[i];
    return this.length;
}

Array.prototype.find = function(value, start) {
    start = start || 0;
    for (var i=start; i<this.length; i++)
        if (this[i]==value)
            return i;
    return -1;
}

Array.prototype.has = function(value) {
    return this.find(value)!==-1;
}

// FUNCTIONAL

function map(list, func) {
    var result = [];
    func = func || function(v) {return v};
    for (var i=0; i < list.length; i++) result.push(func(list[i], i, list));
    return result;
}

function filter(list, func) {
    var result = [];
    func = func || function(v) {return v};
    map(list, function(v) { if (func(v)) result.push(v) } );
    return result;
}


// DOM

function getElem(elem) {
    if (document.getElementById) {
        if (typeof elem == "string") {
            elem = document.getElementById(elem);
            if (elem===null) throw 'cannot get element: element does not exist';
        } else if (typeof elem != "object") {
            throw 'cannot get element: invalid datatype';
        }
    } else throw 'cannot get element: unsupported DOM';
    return elem;
}

function hasClass(elem, className) {
    return getElem(elem).className.split(' ').has(className);
}

function getElementsByClass(className, tagName, parentNode) {
    parentNode = !isUndefined(parentNode)? getElem(parentNode) : document;
    if (isUndefined(tagName)) tagName = '*';
    return filter(parentNode.getElementsByTagName(tagName),
        function(elem) { return hasClass(elem, className) });
}


// DOM EVENTS

function listen(event, elem, func) {
    elem = getElem(elem);
    if (elem.addEventListener)  // W3C DOM
        elem.addEventListener(event,func,false);
    else if (elem.attachEvent)  // IE DOM
        elem.attachEvent('on'+event, function(){ func(new W3CDOM_Event(elem)) } );
        // for IE we use a wrapper function that passes in a simplified faux Event object.
    else throw 'cannot add event listener';
}

function mlisten(event, elem_list, func) {
    map(elem_list, function(elem) { listen(event, elem, func) } );
}

function W3CDOM_Event(currentTarget) {
    this.currentTarget  = currentTarget;
    this.preventDefault = function() { window.event.returnValue = false }
    return this;
}

// MISC CLEANING-AFTER-MICROSOFT STUFF
function isUndefined(v) {
    var undef;
    return v===undef;
}

//<--lib ends

//Our functions starts....

//Open popup. Can be called directly
function Popup(url, target, features)
{
	var theWindow = window.open(url, target, features);
	theWindow.focus();
	return theWindow;
}
//Holder for Popup(). As it's to be registered with event listener
function PopupHolder(e)
{
	Popup(e.currentTarget.getAttribute('href'), e.currentTarget.getAttribute('target') || J_POPUP_TARGET, J_POPUP_FEATURES);
	e.preventDefault();
}
//show balloon. Can be called directly
function ShowBalloon(objA, x, y)
{
	gTmp_ATitle = objA.title; //preserve the title in global var
	objA.title = ''; //empty it, so that it won't popup
	var tmp_title = 'Help', tmp_desc = gTmp_ATitle, pos_colon; //safe init
	//e.g., gTmp_ATitle = 'Help: Help is a help...'
	if ((pos_colon=gTmp_ATitle.indexOf(':')) !=-1 )
		{
			tmp_title = gTmp_ATitle.substring(0, pos_colon);
			tmp_desc = gTmp_ATitle.substring(pos_colon+1);
		}
	var balloon = document.getElementById(J_BALLOON);
	balloon.className = J_CLSBALLOON;
	balloon.style.display = 'inline';
	balloon.style.width = J_BALLOONWIDTH + 'px';
	balloon.style.top = y + 'px';
	balloon.style.left = x + 'px';
	balloon.innerHTML = '<span class="' + J_CLSBALLOONTITTLE + '">'+ tmp_title +'<\/span><div class="' + J_CLSBALLOONDESC + '">'+ tmp_desc + '<\/div>';
	return true;
}
//For the links in myPhotos.php
function ShowPhotoBalloon(objA, x, y)
{
	gTmp_ATitle = objA.title; //preserve the title in global var
	objA.title = ''; //empty it, so that it won't popup
	var tmp_title = 'Help', tmp_desc = gTmp_ATitle, pos_colon; //safe init
	//e.g., gTmp_ATitle = 'Help: Help is a help...'
	if ((pos_colon=gTmp_ATitle.indexOf(':')) !=-1 )
		{
			tmp_title = gTmp_ATitle.substring(0, pos_colon);
			tmp_desc = gTmp_ATitle.substring(pos_colon+1);
		}
	var balloon = document.getElementById(J_BALLOON);
	balloon.className = J_CLSPHOTOLINKBALLOON;
	balloon.style.display = 'inline';
	balloon.style.width = J_PHOTOBALLOONWIDTH + 'px';
	balloon.style.top = y + 'px';
	balloon.style.left = x + 'px';
	balloon.innerHTML = '<div class="' + J_CLSPHOTOBALLOONTEXT + '">'+ tmp_desc + '<\/div>';
	return true;
}
//Holder for ShowBalloon(). As it's to be registered with event listener
function ShowPhotoLinkBalloonHolder(e)
{
	var posx = 0, posy = 0;
	if (e.pageX || e.pageY) //Moz
		{
			posx = e.pageX;
			posy = e.pageY;
		}
	 else if (event.clientX || event.clientY) //IE. Note: event.x not working fine
		{
			posx = event.clientX + document.body.scrollLeft;
			posy = event.clientY + document.body.scrollTop;
		}
	//Note: using the x, y as it is cause the div to flicker in certain border points in FF (IE, Opera works find).
	ShowPhotoBalloon(e.currentTarget, posx+J_BALLOONPOSADJX, posy+J_BALLOONPOSADJY);
	e.preventDefault();
}
//Holder for Links in myPhotos.php page
function getAbsoluteOffsetTopConfirmation(obj){
	var top = obj.offsetTop;
	var parent = obj.offsetParent;
	while (parent != document.body)
		{
			top += parent.offsetTop;
			parent = parent.offsetParent;
		}
	return top;
}

function getAbsoluteOffsetLeftConfirmation(obj){
	var left = obj.offsetLeft;
	var parent = obj.offsetParent;
	while (parent != document.body)
		{
			left += parent.offsetLeft;
			parent = parent.offsetParent;
		}
	return left;
}
function ShowBalloonHolder(e)
{
	var posx = 0, posy = 0;
	if (e.pageX || e.pageY) //Moz
		{
			posx = e.pageX;
			posy = e.pageY;
		}
	 else if (event.clientX || event.clientY) //IE. Note: event.x not working fine
		{
			if(document.body.scrollTop==0){
				var targetText = e.currentTarget;
				targetText = targetText + "";
				targetText = targetText.substring(targetText.indexOf('#')+1);
				targetText = 'Help_'+targetText;
				targetText = document.getElementById(targetText);
				var posy = getAbsoluteOffsetTopConfirmation(targetText);
				var posx = getAbsoluteOffsetLeftConfirmation(targetText);
				//alert(posx+'--'+posy+J_BALLOONPOSADJX);
			}
			else{
				posx = event.clientX + document.body.scrollLeft;
				posy = event.clientY + document.body.scrollTop;
			}
		}
	//Note: using the x, y as it is cause the div to flicker in certain border points in FF (IE, Opera works find).
	ShowBalloon(e.currentTarget, posx+J_BALLOONPOSADJX, posy+J_BALLOONPOSADJY);
	e.preventDefault();
}
//Hides balloon.
function HideBalloon(objA)
{
	var balloon = document.getElementById(J_BALLOON);
	balloon.style.display = 'none';
	objA.title = gTmp_ATitle; //re-assign
}
//Holder for HideBaloon. As it's to be registered with event listener
function HideBalloonHolder(e)
{
	HideBalloon(e.currentTarget);
	e.preventDefault();
}
//Function for mailCompose.php, used to set value in username textbox
function setUserName(frmObj)
{
	if (frmObj.contacts.value == '')
		{
			return;
		}
	email_address_value = replaceEmailAddress(frmObj.username.value, frmObj.contacts);
	email_address_value = replaceEmailFriend(email_address_value, frmObj.contacts);
	if (email_address_value.indexOf(',') == -1 && email_address_value != '')
		{
			email_address_value = email_address_value + ', ';
		}
	frmObj.username.value = email_address_value + frmObj.contacts.value + ', ';
	frmObj.username.focus();
}
function replaceEmailAddress(email_address_value, email_groups)
{
	email_address_value = email_address_value.replace(', '+email_groups.value,'');
	email_address_value = email_address_value.replace(email_groups.value+', ','');
	email_address_value = email_address_value.replace(email_groups.value,'');
	return email_address_value;
}
function replaceEmailFriend(email_address_value, email_friends)
{
	email_address_value = email_address_value.replace(', '+email_friends.value,'');
	email_address_value = email_address_value.replace(email_friends.value+', ','');
	email_address_value = email_address_value.replace(email_friends.value,'');
	return email_address_value;
}

// Function to select all check boxes
// called in mailInbox.php, mailSent.php, mailSaved.php, mailTrash.php
function selectAll(thisForm)
	{
		for (var i=0; i<thisForm.elements.length; i++)
			{
				if (thisForm.elements[i].type == "checkbox")
					{
						if(thisForm.checkall.checked)
							{
								thisForm.elements[i].checked=true;
							}
							else
								{
									thisForm.elements[i].checked=false;
								}
					}
			}
	}
//code execution starts here...

//global vars
var gTmp_ATitle; //temp variable to hold and swap title attributes
//global constants. Used to change behaviors quickly
//presumably IE doesn't support const on strings
var J_BALLOON = 'balloon'; //balloon id
var J_CLSHELP = 'clsHelp';
var J_CLSBALLOON = 'clsBalloon';
var J_CLSBALLOONTITTLE = 'clsBalloonTittle';
var J_CLSBALLOONDESC = 'clsBalloonDesc';
var J_BALLOONPOSADJX = 10;
var J_BALLOONPOSADJY = 10;
var J_POPUP_FEATURES = 'location=0,statusbar=0,menubar=0,scrollbars=1';
var J_POPUP_TARGET = 'help';
var J_BALLOONWIDTH = 200;
var J_CLSPHOTOLINKCLASS = 'clsPhotoVideoEditLinks';
var J_CLSPHOTOLINKBALLOON = 'clsPhotoBalloon';
var J_CLSPHOTOBALLOONTEXT = 'clsPhotoBalloonText';
var J_PHOTOBALLOONWIDTH = '90';

var total_baloons=0;
listen('load',
		window,
		function()
		{
			//create balloon div...
			var balloon = document.createElement('div');
			balloon.id = J_BALLOON;
			document.body.appendChild(balloon);
			//listen...
			mlisten('mouseover', getElementsByClass(J_CLSHELP,'a'), ShowBalloonHolder);
			mlisten('mouseout', getElementsByClass(J_CLSHELP,'a'), HideBalloonHolder);
			mlisten('click', getElementsByClass(J_CLSHELP,'a'), PopupHolder);
			mlisten('mouseover', getElementsByClass(J_CLSPHOTOLINKCLASS,'a'), ShowPhotoLinkBalloonHolder);
			mlisten('mouseout', getElementsByClass(J_CLSPHOTOLINKCLASS,'a'), HideBalloonHolder);
		}
	);

//	====Need cssQuery and Behaviour====

/**
 * @author		rajesh_04ag02
 * @copyright	Copyright (c) 2005-2006 {@link http://www.agriya.com Agriya Infoway}
 * @version		SVN: $Id: script.js 2796 2006-12-04 08:15:27Z selvaraj_35ag05 $
 * @todo		Possibly replace help tips' libs with Behaviour
 */

//oh my, holy hack http://groups.google.com/group/comp.lang.javascript/msg/923c83ebf78b818a
//CSS2 browsers require 'table-row-group' to display tbody tag properly
//Note: if IE display.style is set to 'table-row-group', it will bug with "Error: Could not get the display property. Invalid argument."
var display_tbl_block = (document.all) ? 'block' : 'table-row-group';
var catch_rules =
	{
		//for admin/depositPlans.php toggling of options...
		'#adminuserProfilesEdit #usr_status' : function(element)
		{
			document.getElementById("activate_user_block").style.display = (element.value=="0-Ok") ? display_tbl_block : 'none';
			//onchange show it only for appropriate values...
			element.onchange = function()
			{
				document.getElementById("activate_user_block").style.display = (this.value=="0-Ok") ? display_tbl_block : 'none';
			}
		}
	};
//Behaviour.register(catch_rules);

function CloseButton()
	{
		window.close();
	}

function openVid(filename, video_id)
	{
		//var path = filename;
		//window.open (path, "","status=0,toolbar=0,resizable=0,scrollbars=0");
		var foo = window.open(filename,'_blank','status=0,toolbar=0,resizable=0,scrollbars=0');
		foo.moveTo(0,0);
		foo.resizeTo(screen.availWidth,screen.availHeight);
	}

function trim(str){
    return str.replace(/^(\s+)?(\S*)(\s+)?$/, '$2');
}

function ltrim(str){
    return str.replace(/^\s*/, '');
}

function rtrim(str){
    return str.replace(/\s*$/, '');
}

function showHide(show_id, link_id, on_class, off_class){
	if(obj = document.getElementById(show_id)){
		if(obj.style.display=='none'){
			obj.style.display='';
			if(obj1 = document.getElementById(link_id)){
				obj1.className = off_class;
			}
			return false;
		}
		obj.style.display='none';
		if(obj1 = document.getElementById(link_id)){
			obj1.className = on_class;
		}
	}
	return false;
}

function togggleThis(show_id){
	if(obj = document.getElementById(show_id))
		{
			if(obj.style.display=='none')
				obj.style.display='';
				else
					obj.style.display='none';
		}
}

function ShowBaloon(id,hide_option)
	{
		var hide_count=false;
		for(var no=0;no<=total_baloons;no++)
			{
				if(no != id)
					{
				var divs = document.getElementById('selCoolMemberActive_'+no);
				divs.style.display='none';
					}
			}
		if(hide_option!='hideall')
			{
				var divs = document.getElementById('selCoolMemberActive_'+id);
				divs.style.display='block';
			}
	}
function initializeBalloons(total)
	{
		total_baloons=total;
	}

function showHideLnBar(show_id, link_id, on_class, off_class, url)
	{
		if(obj = document.getElementById(show_id))
			{
				if(obj.style.display=='none')
					{
						obj.style.display='';
						if(obj1 = document.getElementById(link_id))
							{
								obj1.className = off_class;
							}
						//--Start AjaxUpater----
						var pars='lnbar='+show_id;
						var method_type='get';
						var myAjax = new Ajax.Request(
							url,
							{
							method: method_type,
							parameters: pars,
							onComplete: generateResponse
							});
						//-End AjaxUpdater------
						return false;
					}
				obj.style.display='none';
				if(obj1 = document.getElementById(link_id))
					{
						obj1.className = on_class;
					}
			}
		return false;
	}
function generateResponse(originalRequest)
	{
		return true;
	}
function show(element){
	if(obj = document.getElementById(element))
		obj.style.display = '';
}
function hide(element){
	if(obj = document.getElementById(element))
		obj.style.display = 'none';
}

/**
 *
 * @access public
 * @return void
 **/
function setClass(li_id, li_class)
{
	document.getElementById(li_id).setAttribute('className',li_class);
	document.getElementById(li_id).setAttribute('class',li_class);
}

function isObject(arg){
		return (typeof arg =='object');
}
function isset(varSet){
	return true;
}
function isValidXmlDocument(doc){
		return (isObject(doc) && isset(doc.nodeType) && (doc.nodeType==9) && (doc.documentElement!=null));
}

//For sorting
function changeOrderbyElements(form_name,field_name){
	 	var obj = eval("document."+form_name+".orderby_field");
	 	obj.value = field_name;
	 	obj = eval("document."+form_name+".orderby");
	 	if(obj.value=="asc")
	 		obj.value="desc";
	 	else
	 		obj.value="asc";
	 	eval("document."+form_name+".submit()");
	 	return false;
	}

//for postmethod to paging
function pagingSubmit(formname, start){
	var obj = eval("document."+formname);
	obj.start.value = start;
	obj.submit();
	return false;
}

function addComment(url, first_par, form_name, divname)
	{
		Ajax.Responders.unregister(myGlobalHandlers);
		commet_str = $F('comment')
		commet_str = commet_str.replace( /^\s+/g, "" );
  		commet_str =  commet_str.replace( /\s+$/g, "" );
		if (commet_str.length == 0)
			{
				alert("Enter comment");
				return false;
			}

		pars = Form.serialize(form_name);
		pars = first_par + pars;
		var myAjax = new Ajax.Updater(
								{success: divname},
								url,
								{
									method: 'post',
									parameters: pars
								});
		form_name.reset();
	}
//Ajax
// sample url = 'http://yourserver/app/get_sales';
// sample pars = 'empID=' + empID + '&year=' + y;
// sample method_type = 'post'
function chnageContentFilter(url, pars, method_type)
	{
		var myAjax = new Ajax.Request(
							url,
							{
							method: method_type,
							parameters: pars,
							onComplete: chnageContentFilterResponse
							});
	}
var session_check = 'heck|||||||||valid|||||||||login';
var session_check_replace = 'check|||||||||valid|||||||||login';
function chnageContentFilterResponse(originalRequest){
		var data = originalRequest.responseText;
		if(data.indexOf(session_check)>=1)
			{
				data = data.replace(session_check_replace,'');
			}
		else
			{
				return;
			}
		if(data)
			{
				var url = location.href;
				url = url.replace('#','');
				window.location = url;
				$('selContentFilterStatus').innerHTML = data;
			}
	}
function popupWindowUpload(url){
	window.open (url, "","status=0,toolbar=0,resizable=0,scrollbars=1");
}
function changeCategoryRequest(url, pars, method_type)
	{
		var myAjax = new Ajax.Request(
							url,
							{
							method: method_type,
							parameters: pars,
							onComplete: changeCategoryResponse
							});
	}
function changeCategoryResponse(originalRequest){
		var data = originalRequest.responseText;
		if(data.indexOf(session_check)>=1)
			{
				data = data.replace(session_check_replace,'');
			}
		else
			{
				return;
			}
		if(data)
			{
				$('selCategoryList').innerHTML = data;
			}
	}
function populateSubCategoryRequest(url, pars, method_type)
	{
		var myAjax = new Ajax.Request(
							url,
							{
							method: method_type,
							parameters: pars,
							onComplete: populateSubCategoryResponse
							});
	}
function populateSubCategoryResponse(originalRequest){
		var data = originalRequest.responseText;
		if(data.indexOf(session_check)>=1)
			{
				data = data.replace(session_check_replace,'');
			}
		else
			{
				return;
			}
		if(data)
			{
				$('selSubCategoryBox').innerHTML = data;
			}
	}

//avatar
function ajaxUpdateDiv(url, pars, divname){
    
	var myAjax = new Ajax.Updater(
									{success: divname},
									url,
									{
										method: 'post',
										parameters: pars
									});
}
function showAvatars(url, pars, divname){
	if ($('loadingAvatars1'))
		$('loadingAvatars1').innerHTML = processingSrc;
	if ($('loadingAvatars2'))
		$('loadingAvatars2').innerHTML = processingSrc;
	ajaxUpdateDiv(url, pars, divname);
	$('showSuccess').hide();
}
/**
 *
 * @access public
 * @return void
 **/
function updateAvatar(img_id, url, img_src){
		$('selPlainImage').innerHTML = '<img src="'+img_src+'" />';
		ok = confirm('Are you sure you want to change your avatar?');
		if(ok){
			setClassName(img_id);
			pars = 'ajax_page=1'+'&avatar_id='+img_id;
			method_type='post';
			var myAjax = new Ajax.Request(
								url,
								{
								method: method_type,
								parameters: pars
								});
		}
}
function updateAvatarForSignup(img_id,user_id,url, img_src){
		$('selPlainImage').innerHTML = '<img src="'+img_src+'" />';
		//ok = confirm('Are you sure you want to change your avatar?');
		//if(ok){
			setClassName(img_id);
			pars = 'ajax_page=1'+'&avatar_id='+img_id+'&user_id='+user_id;
			method_type='post';
			var myAjax = new Ajax.Request(
								url,
								{
								method: method_type,
								parameters: pars
								});
		//}
}
function setClassName(img_id)
		{
			if ($('selected_avatar_id').value != '')
				{
					selectedDivId = 'selAvatar_'+$('selected_avatar_id').value;
					$(selectedDivId).removeClassName('clsActiveAvatorImage')
					$(selectedDivId).removeClassName('clsImageAvator')
				}
			selectedDivId = 'selAvatar_'+img_id;
			$(selectedDivId).addClassName('clsActiveAvatorImage');
			$(selectedDivId).addClassName('clsImageAvator');
			$('selected_avatar_id').value = img_id;
			$('showSuccess').addClassName('clsConfirmPopup');//class="clsActiveAvatorImage clsImageAvator"
			$('showSuccess').show();
			//$('selMsgSuccess').hide();
			if($('selMsgSuccess'))
				$('selMsgSuccess').hide();
			return true;
		}
//avatar
function populatePriceTypeRequest(url, pars, method_type)
	{
		var myAjax = new Ajax.Request(
							url,
							{
							method: method_type,
							parameters: pars,
							onComplete: populatePriceTypeResponse
							});
	}
function populatePriceTypeResponse(originalRequest){
		var data = originalRequest.responseText;
		if(data.indexOf(session_check)>=1)
			{
				data = data.replace(session_check_replace,'');
			}
		else
			{
				return;
			}
		if(data)
			{

				$('selPriceTypeBox').innerHTML = data;
			}
	}

