/** CLASS TO PREVENT FLASH OF UNSTYLED CONTENT **/
document.write('<style type="text/css">.hide{display:none;}</style>')



/** FormSubmitter is a generic class to submit forms via AJAX
 * It works like this:
 * 1. Create the html form 'u_formname_form', you do not need to include an onsubmit property
 * 2. Create a php file in the BASEURL folder with the name 'u_formname.php' to
 *	  handle the form submission. ($_POST['submitMethod'] will == ajax)
 * 3. If you want a simple element replacement, init with submitAction=elementid and type='Updater'
 * 4. If you want to do something with the return, add it to a list instead of replacing the whole
 *    thing, for instance, init with submitAction=yourjavascriptfunction passed as an object 
 *    and type='Request'
 *
 * note, the prefix for formname is a convention only
 *   u_  == update
 *   i_  == insert
 *   d_  == delete
 *   s_  == select 
 * Requires prototype.js http://prototype.conio.net/
 * Based on an example from http://www.sergiopereira.com/articles/prototype.js.html
 */
var FormSubmitter = jQuery.Class.create();
FormSubmitter.prototype = {

	init: function(frm, submitAction, type) {
		this.frm = frm;
		this.action = null;
		this.resetForm = true;
		if(arguments.length > 3) 
			this.action = arguments[3];

		this.submitAction = submitAction;
		this.type = type;
		//assigning our method to the event
		jQuery(this.frm).bind('submit', {obj: this}, this.submitform);
		//this.frm.onsubmit = this.submitform.bindAsEventListener(this);
		if (this.frm != null && this.frm.submitMethod != null)
			this.frm.submitMethod.value = 'ajax';
		
	},
  
  
  /** 
   * hijack original callback, decode the JSON response if needed, then call the original callback
   *
   *  this is causing problems in IE, so forget it for now
   *
	callback: function(t) {
		debugger;
		if( t.charAt(0) == '{' ) { // a first character as a { denotes a JSON response
			var jsonObj = eval('(' + t + ')');
			this.clientCallback( jsonObj );
		}
		else {
			this.clientCallback( t );
		}
	}, */ 
   
	submitform: function(evt) {
		var obj = this;
		if (null != evt) {
			if(evt.data != null && evt.data.obj != null)
				obj = evt.data.obj;
		}
		var url = obj.action;
		if(url == null)
			url = obj.frm.action;

		//build the POST query
		submitdata = "submitMethod=ajax"; 
		for (i=0; i < obj.frm.elements.length; i++) {
			//skip what we don't need, ESPECIALLY don't include submitMethod=normal
			if(obj.frm.elements[i].name != 'submitMethod' && obj.frm.elements[i].name != 'submit') {
				if(obj.frm.elements[i].type == 'checkbox' || obj.frm.elements[i].type == 'radio') {
					if(obj.frm.elements[i].checked) {
						submitdata += "&" + obj.frm.elements[i].name + "=" + encodeURIComponent(obj.frm.elements[i].value);
					}   
				} else {
					submitdata += "&" + obj.frm.elements[i].name + "=" + encodeURIComponent(obj.frm.elements[i].value);
				}
			}
		}
		
		if(obj.type == "Request") {
			var foo = jQuery.ajax({url: url, type:'post', data:submitdata, success:obj.submitAction, error:errFunc});
		} else {
			new jQuery.ajax({url: url, type:'post', data:submitdata, error:errFunc});
		}
		if(obj.resetForm)
		    obj.frm.reset();
		
		return false;
	}, 

	buildurl: function() {
		alert('ac ' + this.frm.action);
		var fa = this.frm.action.split('/');
		
		var tmp = '';
		while(tmp == '') {
			tmp = fa.pop();
		}
		return window.location.protocol + '//' 	+ window.location.host + '/' + tmp + '/';
	}
};

/**
 * Return the string value -- from the localization table
 * @return value if found, key if not found
 */
function localString (key)
{
	if (language == null)
		return key;
	
	var val = language[key];
	if (val == null)
		return key;
	else
		return val;
}

// To fix Transparent overlay dimensions 
function fixOverlay(){

	var pageHeight = document.body.scrollHeight;
	var overlayElement = document.getElementById('overlay_signin');
	document.getElementById('overlay_signin').style.height = (70+pageHeight)+'px';
	var obj_body = document.getElementsByTagName("html");
	//obj_body[0].style.overflow = "hidden";

	
}

function fixOverlayHeight(){

	//iecompattest() iecompattest().scrollTop + 'px';
	var elemName = 'overlay_signin';
	if(arguments.length == 1) { 
		elemName = arguments[0]; 
	}
	var pageHeight = document.body.scrollHeight;
	var pageWidth = document.body.scrollWidth;
	var overlayElement = document.getElementById(elemName);
	overlayElement.style.height = (70+pageHeight)+'px';
	overlayElement.style.width = pageWidth + 'px';
	//var obj_body = document.getElementsByTagName("html");
	//obj_body[0].style.overflow = "hidden";
	
}

// Show Hide Overlay
/*
function hideElem(id){
	var elem = document.getElementById(id);
	elem.style.display = 'none';
		
}

function showElem(id){
	var elem = document.getElementById(id);
	elem.style.display = 'block';
}

*/

function textAreaMaxLength(obj, maxlength, indDivId){
	
	if(obj.value.length > maxlength)
	{
	
		obj.value = obj.value.substr(0,maxlength);
	}
	if(indDivId) {
		charleft = maxlength - obj.value.length;
		document.getElementById(indDivId).innerHTML = charleft;
	}
}
function print_r(theObj){
  if(theObj.constructor == Array ||
     theObj.constructor == Object){
    document.write("<ul>")
    for(var p in theObj){
      if(theObj[p].constructor == Array||
         theObj[p].constructor == Object){
document.write("<li>["+p+"] => "+typeof(theObj)+"</li>");
        document.write("<ul>")
        print_r(theObj[p]);
        document.write("</ul>")
      } else {
document.write("<li>["+p+"] => "+theObj[p]+"</li>");
      }
    }
    document.write("</ul>")
  }
}



/**
 * field is just there to let the class know which
 *    field to return (since it doesn't necessarily know
 *    which field changed)
 */
var ipeCallback = function(field) {
	return '&field='+field+'&submitMethod=ajax';
};

var errFunc = function(t) {
    alert('Error ' + t.status + ' -- ' + t.statusText);
};


var postMetatags = function() {
	var frm = document.forms['metatag_form']; 
	var url = BASEURL+'u_meta.php';
	var submitdata = "hid=" + frm.elements['hid'].value 
		+ "&cid=" + frm.elements['cid'].value
		+ "&metatags=" + frm.elements['metatags'].value
		+ "&submitMethod=ajax";
	
	new jQuery.ajax({url: url, type:'post', data:submitdata, 
					success: function(t){
						document.getElementById('tags').innerHTML=t;
					}, 
					error:errFunc
		});

	if(this.resetForm)
        frm.reset();
	return false;
};

/**
 * from quirksmode.org
 * link: http://www.quirksmode.org/js/findpos.html  
 */
function findPos(obj) {
	var origional = obj;
	var pos = new Object();
	pos.left = pos.top = 0;
	
	if (obj.offsetParent) {
		pos.left = obj.offsetLeft
		pos.top = obj.offsetTop
		while (obj = obj.offsetParent) {
			pos.left += obj.offsetLeft
			pos.top += obj.offsetTop
		}
	}
	
	pos.right = pos.left + origional.offsetWidth;
	pos.bottom = pos.top + origional.offsetHeight;
	return pos;
}

/**
 * Popup Functions
 */
function popupHide(boxname) {
	document.getElementById(boxname).style.display = 'none';
}

var popup = jQuery.Class.create();
popup.prototype = {
	init: function(boxname, pos) {
		this.boxname = boxname;
		this.pos = pos;
	}
}

/**
* a collection of popUp windows that can only be shown one at a time.
* I.e. opening one of the popups closes all the others in the collection
*/
var popupCollection = jQuery.Class.create();
popupCollection.prototype = {
	init: function() {
		this.popups = new Object;
	},
	
	/**
	 * boxname - the id of the div to pop up
	 * relative_to - the id of the div to position the pop up relative to
	 * relative_horizontal - [top|bottom], currently ignored
	 * relative_vertical - [left|right], currently ignored
	 */
	add: function(boxname, relative_to, relative_vertical, relative_horizontal) {
		if( ! this.popups[boxname]) {
			var rel = $(relative_to);
			this.popups[boxname] = new popup(boxname, findPos(rel));
		}
		if( 'top' != relative_vertical && 'bottom' != relative_vertical) {
			this.relative_vertical = 'top';
		} else {
			this.relative_vertical = relative_vertical;
		}
		if( 'left' != relative_horizontal && 'right' != relative_horizontal) {
			this.relative_horizontal = 'left';
		} else {
			this.relative_horizontal = relative_horizontal;
		}
	},
	
	show: function(boxname) {
		this.hide();
		var box = document.getElementById(boxname);
		box.style.display = 'block';
		box.style.position = 'absolute';
		if( 'top' == this.relative_vertical ) {
			var _top = this.popups[boxname].pos.top;
			if(!isNaN(_top)) 
				box.style.top = _top + "px";
		} else {
			var _bottom = this.popups[boxname].pos.bottom;
			if(!isNaN(_bottom))
				box.style.top = _bottom + "px";
		}
		if( 'left' == this.relative_horizontal ) {
			var _left = this.popups[boxname].pos.left;
			if(!isNaN(_left))
				box.style.left = _left + "px";
		} else {
			var _right = this.popups[boxname].pos.right;
			if(!isNaN(_right))
				box.style.left = _right + "px";
		}
		
		window.scroll(0, this.popups[boxname].pos.bottom - 50);
		var databox = $(boxname+'data');
	 	if(databox) {
			databox.focus();
			databox.select();
		}
		return false;
	},
	
	hide: function() {
		for( var boxname in this.popups ) {
			document.getElementById(boxname).style.display = 'none';
		}
	}
	
} /* popupCollection */



var changeMobileStep1 = function(t) {
	eval("var resp = " + t);
	if(resp.error_message) {
		alert(resp.error_message);
	} else if(resp.error_messages) {
		alert(resp.error_messages);
	} else {
		changeMobileGoToStep2();
	}
}

var changeMobileStep2 = function(t) {
	eval("var resp = " + t);
	if(resp.error_message) {
		alert(resp.error_message);
	} else if(resp.error_messages) {
		alert(resp.error_messages);
	} else {
		changeMobileGoToStep3();
	}
}

function changeMobileGoToStep1() {
	document.forms.sendvalidatemobile.style.display = 'block';
	document.forms.validatemobile.style.display = 'none';
}
function changeMobileGoToStep2() {
	document.forms.sendvalidatemobile.style.display = 'none';
	document.forms.validatemobile.style.display = 'block';
}
function changeMobileGoToStep3() {
	document.forms.sendvalidatemobile.style.display = 'none';
	document.forms.validatemobile.style.display = 'none';
	$('validatemobile_complete').style.display = 'block';
}
function changeMobileDone() {
	$('change_mobile').style.display = 'none';
   $('send_channel').style.display = 'block';
}


function banner_hide(key) {
	createCookie('banner',key,700);
	$('banner').style.display = 'none';
	$('banner_break').style.display = 'none';
}

function createCookie(name,value,days)
{
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/;domain=" + location.hostname + "";
}

function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name)
{
	createCookie(name,"",-1);
}


function getValue(id,getwhat) {
	var item;
	var btype;
	if (document.getElementById)
	{
		btype ="IE5 NS6 ";
		item = document.getElementById(id);
	}
	else
	{
		if (document.layers)
		{ // Netscape 4
			btype ="NS4 ";
			item = document.id;
		}
		else if (document.all)
		{
			btype ="IE4 ";
			item = document.all(id);
		}
	}
	
	if(item && getwhat == "innerHTML" ) { return item.innerHTML; }
	if(item && getwhat == "value" ) { return item.value; }
	if(item && getwhat == "selectedIndex" ) { return item.options[item.selectedIndex].value; }
	if(item) { return item; }
	
	return false;
}

function reportError()
{
	alert(localString('js_serverdown'));
}

function toggleDiv (id)
{
	if (document.getElementById) { // DOM3 = IE5, NS6
		if (document.getElementById(id).style.display == 'block')
			document.getElementById(id).style.display = 'none';
		else
			document.getElementById(id).style.display = 'block';
	}
	else {
		if (document.layers) { // Netscape 4
			if (document.id.display == 'block')
				document.id.display = 'none';
			else
				document.id.display = 'block';
		}
		else { // IE 4
			if (document.all.id.style.display == 'block')
				document.all.id.style.display = 'none';
			else
				document.all.id.style.display = 'block';
		}
	}
}

function replaceClass(elemId, oldClsName, newClsName)
{
	try
	{
		var elem = document.getElementById(elemId);
		if(elem != null)
		{
			var clsName = elem.className;
			if(oldClsName == null)
				elem.className = clsName + ' ' + newClsName;
			else if(clsName.indexOf(newClsName) < 0)
			{
				if(clsName.indexOf(oldClsName) < 0)
					elem.className = clsName + ' ' +newClsName;									
				else elem.className = clsName.replace(oldClsName, newClsName);
			}
		}
	}
	catch(e)
	{
	}
}

function hidediv(id) {
	replaceClass(id, 'shown', 'hidden');
}



function iecompattest(){
return (document.compatMode!="BackCompat")? document.documentElement : document.body
}


function showdiv(id) {
	replaceClass(id, 'hidden', 'shown');
}



// ajax response

/**
 * a manage function.
 * @author Rohan, I assume
 */
function runAjaxResponsePage(t,showalert)
{
	if ( showalert == 'all') alert("repsonse "+ t);
	eval("var decoded_data = " + t);
	var whichdiv = decoded_data.whichdiv;
	if(whichdiv != '')
	{
		if ( showalert == 'whichdiv' || showalert =='all') alert(whichdiv + '\n' + decoded_data.text);
		document.getElementById(whichdiv).innerHTML = decoded_data.text;
	}
	var js = decoded_data.runJS;
	if(js != '')
	{
		if ( showalert == 'JS' || showalert =='all')    alert('JS ' + decoded_data.runJS);
		eval(decoded_data.runJS);
	}
	
	return ;
}

/* a simple confirm, but if we use this we can expand it later to be a nice
 * pop up box
 */
function hpConfirm(question) {
	return confirm(question);
}

function l3_navigation_change() {
	var f = document.l3_navigation;
	if(f.range) {
		var frange = f.range.options[f.range.selectedIndex].value;
	}
	var ftype = f.type.options[f.type.selectedIndex].value;
	
	var url = f.action;

	if(frange) {
		url += frange + '/' ;
	}
	
	if( ftype != 'alltypes' ) {
		url += ftype + '/';
	}
	document.location = url;
	
}


function featureSwap(type, num) {
   /**
    * the prefix for the swapped divs
    */
	var feafix = 'fea_'+type+'_';

	/**
	 * feafix + i should always exist. But we're going to check anyway.
    */
	var feaverify;

	/**
    * the prefix for the selection thumbnails
    */
	var thmfix = 'fthm_'+type+'_';

	/**
	 * just like the divs, we'll double check that the thumbs exists.
    * avoids possible js errors.
    */
	var thmverify;

	for(var i = 1; i <= 6; i++) {
		feaverify = $(feafix+i)
		if(feaverify) {
			feaverify.style.display = 'none';
		}
		thmverify = $(thmfix+i);
		if(thmverify) {
			thmverify.className = '';
			thmverify.blur();
      }
	}
	$(feafix+num).style.display = 'block';
	$(thmfix+num).className = 'selected';

	return false;
}

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

/**
 *  * Operations to go along with the full view  
 *   */
var fullView = {

    /**
 *      * Show the delete content warning.
 *           */
    deleteContentShow : function(selection) {
        var redirect = window.location.href.toLowerCase();
        var idx = redirect.indexOf('/item/');
        redirect = redirect.substring(0, idx);
        commonActions.deleteContentShow(selection, redirect);
    },

    /**
 *      * Show the add tags dialog for this item.
 *           */
    addTagsShow : function (selection) {
        commonActions.addTagsShow(selection);
    },

    /**
 *      * Change the visibility of an item.
 *           */
    setVisibility : function(vis, selection) {
        commonActions.setContentVisibility(vis,selection);
    }

}

/**
 *  * Operations to go along with the multiselect grid  
 *   */
var multiSelect = {

    /**
 *      * Change all items in the grid to the state of the select all checkbox.
 *           */
    changeAll : function() {
        multiSelect.setAll(document.contentForm.changeAll.checked);
    },

    /**
 *      * Change the checked state of all items in the grid.
 *           * @param checkValue checked state, true or false
 *                */
    setAll : function(checkValue) {
        var objCheckBoxes = document.contentForm.elements['_cids'];
        if(!objCheckBoxes) {
                return;
        }
        var countCheckBoxes = objCheckBoxes.length;
        if(!countCheckBoxes) {
                objCheckBoxes.checked = checkValue;
        } else {
                for(var i = 0; i < countCheckBoxes; i++) {
                    objCheckBoxes[i].checked = checkValue;
                }
        }
    },

    updateChangeAll : function() {
        var objCheckBoxes = document.contentForm.elements['_cids'];
        if(!objCheckBoxes) {
                return;
        }
        var countCheckBoxes = objCheckBoxes.length;
        if(!countCheckBoxes) {
                document.contentForm.changeAll.checked = objCheckBoxes.checked;
        } else {
                var allTrue = true;
                for(var i = 0; i < countCheckBoxes; i++) {
                    if (objCheckBoxes[i].checked == false) {
                        allTrue = false;
                        break;
                    }
                }
            document.contentForm.changeAll.checked = allTrue;
        }
    },

    /**
 *      * Get the list of selected items as an array.
 *           */
    getSelectedArray : function() {
        var selectedcids = new Array();
        var objCheckBoxes = document.contentForm.elements['_cids'];
        if(!objCheckBoxes) {
            return selectedcids;
        }
        var countCheckBoxes = objCheckBoxes.length; // length attribute only exists if multiple checkboxes are present        
        if(!countCheckBoxes) {
            if (objCheckBoxes.checked) {
                selectedcids[0] = objCheckBoxes.value;
            }
        } else {
            var cks = 0;
            for(var i = 0; i < countCheckBoxes; i++) {
                if (objCheckBoxes[i].checked) {
                    selectedcids[cks++] = objCheckBoxes[i].value;
                }
            }
        }
        return selectedcids;
    },

    /**
 *      * Get a comma separated list of selected items.
 *           */
    getSelected : function() {
        var selectedcids = multiSelect.getSelectedArray();
        return multiSelect.implode(selectedcids);
    },

    /**
 *      * Get a comma separated list from an array.
 *           * @param somearray the array to implode
 *                */
    implode : function(somearray) {
        var result = '';
        if (!somearray){
            return result;
        }
        for (i = 0; i < somearray.length; i++) {
            if (i == 0) {
                result = somearray[i];
            } else {
                result = result + ',' + somearray[i];
            }
        }
        return result;
    },

    /**
 *      * Get the selected thumbs.
 *           */
    getSelectedThumbs : function() {
        var result = new Object;
        var sel = multiSelect.getSelected();
        var cids = sel.split(',');
        for (var i=0; i < cids.length; i++)
                if (null == document.getElementById("_img_cid_" + cids[i]))
                        continue;
                else
                        result[i] = document.getElementById("_img_cid_" + cids[i]).src;
        return result;
    },

    /**
 *      * Show the delete content warning.  Check to make sure stuff is selected.
 *           */
    deleteContentShow : function() {
        var selections = multiSelect.getSelected();
        if (selections){
            commonActions.deleteContentShow(selections, window.location.href);
        } else {
            commonActions.showInfo(localString('js_media_delete_none_selected'));
        }
    },

    /**
     * Removes the selected items from the current set   
     */   
    removeFromSetShow : function(sid) {
        var selections = multiSelect.getSelected();
        if (selections){
            commonActions.removeFromSetShow(sid, selections, window.location.href);
        } else {
            commonActions.showInfo(localString('js_sets_missing_item'));
        }
    },

    /**
 *      * Change the visibility of the current selections.
 *           * @param vis the new visibility: public, private, or friends.
 *                */    
    setVisibility : function (vis) {
        var selections = multiSelect.getSelected();
        commonActions.setContentVisibility(vis,selections);
    },

    /**
 *      * Open the widget page with the selected items.
 *           */
    widget : function() {
/*
        var selections = multiSelect.getSelectedArray();
        if (selections.length > 0){
            document.widget_form.cids.value=selections;
            document.widget_form.submit();
        } else {
            document.widget_form.submit();
        }
*/
            document.widget_form.submit();
    },

    /**
 *      * Open the share dialog with the selected items.
 *           */
    share : function() {
        var selections = multiSelect.getSelectedArray();
        if (selections.length > 0){
            shareManager.popupEmail(selections);
        } else {
            commonActions.showInfo(localString('js_share_none_selected'));
        }
    },

    /**
 *      * Open the publish dialog with the selected items.
 *           */
    publish : function() {
        var selections = multiSelect.getSelectedArray();
        if (selections.length > 0){
            shareManager.popupPublish(selections);
        } else {
            commonActions.showInfo(localString('js_publish_none_selected'));
        }
    },

    /**
 *      * Open the slideshow page witht he selected items.
 *           */
    slideshow : function() {
        var selections = multiSelect.getSelectedArray();
        if (selections.length > 0){
            showdiv('overlay_signin');
            so.addVariable("cids", selections);
            so.write("embedCol");
            showdiv('slideshow_box');
        } else {
            commonActions.showInfo(localString('js_slideshow_none_selected'));
        }
    },

    /**
 *      * Unmark as favorites the selected items.
 *           */
    unmarkfav : function () {
        var selections = multiSelect.getSelected();
        commonActions.unmarkfav(selections);
    },
    
    addTagsShow : function () {
        var selections = multiSelect.getSelected();
        if (selections){
            commonActions.addTagsShow(selections);
        } else {
            commonActions.showInfo(localString('js_addtag_none_selected'));
        }
    },

    setCover : function (setId) {
        var selection = multiSelect.getSelected();
        if (selection.toString().search(/^-?[0-9]+$/) == 0){
            commonActions.setCover(setId, selection);
        } else {
            commonActions.showInfo(localString('js_setcover_select_one'));
        }
    }

}

/**
 *  * Operations common to sever areas of the applicaiton  
 *   */
var commonActions = {

    /**
     *  Show the delete content warning dialog.  
     */
    removeFromSetShow : function(sid, cids, redirect) {
        document.getElementById('setremove_redirect').value = redirect;
        document.getElementById('setremove_cids').value = cids;
        document.getElementById('setremove_sid').value = sid;
        showdiv('overlay_signin');
        showdiv('setremove_box');
    },

    /**
    *  Show the delete content warning dialog.  
    */
    removeFromSetSubmit : function() {
        hidediv('overlay_signin');
        hidediv('setremove_box');
        var selections = document.getElementById('setremove_cids').value;
        var redirect = document.getElementById('setremove_redirect').value;
        var sid = document.getElementById('setremove_sid').value;
        if (selections){
            var url = '/manage/sets/editset/' + sid + '/';
            submitdata = "request=ajax&action=deletegroupitem"; 
            submitdata += "&group_id=" + sid + "&item_id=" + selections;	     
            
            new jQuery.ajax({url: url, type:'post', data:submitdata, 
            	success:function (t) {
                if (t == 'ok') {
                    if (redirect) {
                        window.location = redirect;
                    } else {
                        window.location.reload();
                    }
                } else {
                    eval('var data = ' + t); // decode json response
                    if (data.error != null) {
                        commonActions.showError(data.error.message);
                    } else {
                        if (redirect) {
                            window.location = redirect;
                        } else {
                            window.location.reload();
                        }
                    }
                }
            }
            });
 
        } else {
            commonActions.showInfo(localString('js_sets_missing_item'));
        }
    },

    /**
 *      * Change the visibility of content items.
 *           * @param vis the visibility, public, private, or friends
 *                * @param selections the comma separated list of content ids  
 *                     */
    setContentVisibility : function (vis, selections) {
        if (selections){
            var url = '/channel/updatepermissionsmultiple';
            new jQuery.ajax({
                        type: 'post',
		 	   url: url,
                        data: 'submitMethod=ajax&content_id='+selections+'&share='+vis,
                        success: function(t) {
                                if (t == 'ok') {
									var message = "";
									if(vis == 'public')
										message = localString('js_make_public_successfully');
									else if(vis == 'private')
										message = localString('js_make_private_successfully');
									else if(vis == 'friends')
										message = localString('js_make_friend_successfully');											
                                    commonActions.showInfo(message, localString('js_success')); //Success
                                } else {
                                    eval('var data = ' + t); // decode json response
                                    if (data.error != null) {
                                        commonActions.showError(data.error.message);
                                    } else {
                                        window.location.reload();
                                    }
                                }
                        }
                });
        } else {
            commonActions.showInfo(localString('js_perm_select_atleast_one_item'));
        }
    },

    /**
 *      * Show the delete content warning dialog.  
 *           */
    deleteContentShow : function(cids, redirect) {
        document.getElementById('delete_redirect').value = redirect;
        document.getElementById('delete_cids').value = cids;
        showdiv('overlay_signin');
        showdiv('delete_box');
 	 fixOverlayHeight();
    },

    /**
 *      * Delete content items.
 *           * @param comma separated list of content ids  
 *                */
    deleteContentSubmit : function() {
        hidediv('overlay_signin');
        hidediv('delete_box');
        var selections = document.getElementById('delete_cids').value;
        var redirect = document.getElementById('delete_redirect').value;
        if (selections){
            var url = '/channel/deletemultiple';
	     submitdata = "submitMethod=ajax"; 
            submitdata += "&content_id=" + selections;
	     
	     new jQuery.ajax({url: url, type:'post', data:submitdata, 
            	success:function (t) {            
                if (t== 'ok') {
                    if (redirect) {
                        window.location = redirect;
                    } else {
                        window.location.reload();
                    }
                } else {
                    eval('var data = ' + t); // decode json
															// response
                    if (data.error != null) {
                        commonActions.showError(data.error.message);
                    } else {
                        if (redirect) {
                            window.location = redirect;
                        } else {
                            window.location.reload();
                        }
                    }
                }
        }, error:reportError});
        } else {
            commonActions.showInfo(localString('js_media_delete_none_selected'));
        }
    },
    
    /**
 *      * Show the add tag dialog for a set of cids.  
 *           * @param cids a comma separated list of content ids to apply tags to
 *                */
    addTagsShow : function(cids) {
        document.getElementById('addtag_tags').value = '';
        document.getElementById('addtag_cids').value = cids;
		document.getElementById('submitTag').disabled = true;
        showdiv('overlay_signin');
        showdiv('addtag_box');
		fixOverlayHeight();
    },
    
    enableTagsButton : function() {
    	var tags = document.getElementById('addtag_tags').value;
 		if(tags == "" || tags.length <= 0){
 			document.getElementById('submitTag').disabled = true;
 		} else {
 			document.getElementById('submitTag').disabled = false;
 		}
    },	
    /**
 *      * Add tags to a list of content ids.
 *           */    
    addTagsSubmit : function () {
        var tags = document.getElementById('addtag_tags').value;
		if(tags == "" || tags.length <= 0){
			document.getElementById('submitTag').disabled = true;
			return;
		}
        var selections = document.getElementById('addtag_cids').value;
        if (tags){
            if (selections){
                var url = '/channel/addtagsmultiple';
                
                submitdata = "submitMethod=ajax"; 
            	submitdata += "&content_id=" + selections + "&tag=" + tags; 
            	            	
            	new jQuery.ajax({url: url, type: 'post', data: submitdata, 
            					success: function(t) {
            						hidediv('overlay_signin');
            						hidediv('addtag_box');
            						if (t == 'ok') { 
                                        commonActions.showInfo(localString('js_tag_added_successfully'), localString('js_success')); //Success
                                    } else {
                                        eval('var data = ' + t); // decode json response
                                        if (data.error != null) {
                                            commonActions.showError(data.error.message); //Error
                                        } else {
                                            commonActions.showInfo(localString('js_tag_added_successfully'), localString('js_success')); //Success
                                        }
    									return;
                                    }
            					}	
            	});

            } else {
                commonActions.showInfo(localString('js_addtag_none_selected'));
            }
        } else {
            return;
        }
    },

    /**
     *      * Update user status to a list of content ids.
     *           */    
    updateUserStatus : function () { 
    	
    	var userStatus = document.getElementById('userStatus').value;
   		var url = '/statusmsg/add';
                        
		submitdata = "submitMethod=ajax&can_update_status=1&submit=Submit"; 
        submitdata += "&new_status_msg=" + userStatus; 
                	            	
		new jQuery.ajax({url: url, type: 'post'
				, data: submitdata
				, success: function(t) {
					hidediv('overlay_signin');
                	hidediv('statsMsg_box');
                	try {
					eval('var data = ' + t); // decode json response
					if (data.errorMessage != null) {
						commonActions.showError(data.errorMessage); //Error
					} else {
						var elem = document.getElementById('userStatusMessagePanel');
						if(elem != null)
							elem.innerHTML = data.posted_status_msg;												
						commonActions.showInfo(localString('js_userStatus_updated_successfully'), localString('js_success')); //Success
					}}catch(e){}
					return;
				 }	
                }); 
    },	
	    /**
 *      *  Active/Inactive the add tag button & submit tag on Enter Key.  
 *           * @param keyCode key pressed by user
*	      *		    obj object id that needs to submitted
 *                */
    addTags : function(keyCode, obj) {
		var elem = document.getElementById(obj);
		if(elem.value == "" || elem.value.length <= 0){
			elem.disabled = true;
			return;
		} else if(elem.disabled) {
			elem.disabled = false;
		}
		if(keyCode != 13) 
			return;		
		commonActions.addTagsSubmit();
    },
    
    /**
     * set cover image for set
     * @param setId id of the set
     * @param contentId id of the content to use
     *
     */
    setCover : function(setId, contentId) {
	changeGroupIcon('sets', 'parent', setId, 'images' + contentId);    
    },
    /**
 *      * Unmark as favorites the list of content ids.
 *           * @param selections the comma separated list of content ids
 *                */
    unmarkfav : function (selections) {
        if (selections){
            var url = '/favorites/remove';
            submitdata = "submitMethod=ajax"; 
        	submitdata += "&content_id=" + selections ; 
        	            	
        	new jQuery.ajax({url: url, type: 'post', data: submitdata, 
        					success: function(t) {
                				eval('var data = ' + t.responseText); // decode json response
                				if (data.error != null) {
                					commonActions.showError(data.error.message); // Error
                				} else {
                					window.location.reload(); // Success
                				}
        				}	
        		});
        	

        } else {
            commonActions.showInfo(localString('js_unfavorite_none_selected'));
        }
    },

    /**
 *      * Show the error dialog.
 *           * @param message the message to display
 *                * @param title teh dialog title  
 *                     */
    showError : function(message, title) {
        if (title){
            document.getElementById('error_title').innerHTML = title;
        }
        if (message){
            document.getElementById('error_message').innerHTML = message;
        }
        showdiv('overlay_signin');
        showdiv('error_box');
		fixOverlayHeight();
    },

    /**
 *      * Show the information dialog.
 *           * @param message the message to display
 *                * @param title teh dialog title  
 *                     */
    showInfo : function(message, title) {
        if (title){
            document.getElementById('info_title').innerHTML = title;
        }
        if (message){
            document.getElementById('info_message').innerHTML = message;
        }
        showdiv('overlay_signin');
        showdiv('info_box');
		fixOverlayHeight();
    },
    
    /** This is created to prevent javascript errors in IE b/c. there are many places where this function is called, I do not know who deleted that **/
    statsMsg : function() {    	
    }

}

/**
 * Basic Network management (add user to network and remove user from network)
 * @author Josh Schumacher
 */
var networkManager = {
	/**
	 * @param username - the user to add to your network
	 * @param groupIds - comma seperated list of group ids you are adding the user to
	 * @param updateElement - the id of an element on the page to be updated with the AJAX response
	 */
	addUser: function(username, groupIds, updateElement) {
		url = '/manage/network/adduser/'+username;
		submitdata = "submitMethod=ajax&callMethod=ajax"; 
        submitdata += "&action=addNew&groupids_string=" + groupIds + "&updateElementId=" + updateElement;
	 var updateElementId = document.getElementById(updateElement); 
       if (updateElementId ) 
		updateElementId.innerHTML += ' <img src="/images/common/indicator.gif" />';
        new jQuery.ajax({url: url, type: 'post', data: submitdata, 
			success: function(t){
			 if (updateElementId ) 
				updateElementId.innerHTML = t;
		}
});
	},

	/**
	 * @param username - the user to add to your network
	 * @param updateElement - the id of an element on the page to be updated with the AJAX response
	 */
	confirmUser: function(username, updateElement) {
		url = '/manage/network/confirmuser/'+username;
		submitdata = "submitMethod=ajax&callMethod=ajax"; 
        submitdata += "&action=confirm&updateElementId=" + updateElement ;
	 var updateElementId = document.getElementById(updateElement); 
        updateElementId.innerHTML += ' <img src="/images/common/indicator.gif" />';
        new jQuery.ajax({url: url, type: 'post', data: submitdata, 
			success: function(t){
			updateElementId.innerHTML = t;
		}});
	},

	/**
	 * @param username - the user to ignore the friend request from
	 * @param updateElement - the id of an element on the page to be updated with the AJAX response
	 */
	ignoreUser: function(username, updateElement) {
		url = '/manage/network/ignoreuser/'+username;
		submitdata = "submitMethod=ajax&callMethod=ajax"; 
        submitdata += "&action=ignore&updateElementId=" + updateElement ;
	 var updateElementId = document.getElementById(updateElement); 
        updateElementId.innerHTML += ' <img src="/images/common/indicator.gif" />';
        new jQuery.ajax({url: url, type: 'post', data: submitdata, 
			success: function(t){
			updateElementId.innerHTML = t;
		}});	
	},

	/**
	 * @param username - the user to block from a friend request
	 * @param updateElement - the id of an element on the page to be updated with the AJAX response
	 */
	blockUser: function(username, updateElement) {
		url = '/manage/network/blockuser/'+username;
		submitdata = "submitMethod=ajax&callMethod=ajax"; 
        submitdata += "&action=block&updateElementId=" + updateElement ;
	 var updateElementId = document.getElementById(updateElement); 
        updateElementId.innerHTML += ' <img src="/images/common/indicator.gif" />';
        new jQuery.ajax({url: url, type: 'post', data: submitdata, 
			success: function(t){
			updateElementId.innerHTML = t;
		}});	
	},

	/**
	 * @param username - the user to remove from your network
	 * @param updateElement - the id of an element on the page to be updated with the AJAX response
	 */
	removeUser: function(username, updateElement) {
		url = '/manage/network/deleteuser/'+username;
		submitdata = "submitMethod=ajax&callMethod=ajax"; 
        submitdata += "&action=deleteContact&updateElementId=" + updateElement ;
	 var updateElementId = document.getElementById(updateElement); 
        updateElementId.innerHTML += ' <img src="/images/common/indicator.gif" />';
        new jQuery.ajax({url: url, type: 'post', data: submitdata, 
			success: function(t){
			updateElementId.innerHTML = t;
		}});	
	},

	/**
	 * @param username - the user to remove from your network
	 * @param updateElement - the id of an element on the page to be updated with the AJAX response
	 */
	removeUserRefresh: function(username) {
		url = '/manage/network/deleteuser/'+username;
		submitdata = "submitMethod=ajax&callMethod=ajax"; 
        submitdata += "&action=deleteContact" ;        
        new jQuery.ajax({url: url, type: 'post', data: submitdata, 
        	success: function(t) {        
            	if (t) {
            		window.location.reload();
            	}
            }
        });
	}
}



// JQUERY STUFF_______________________________________________________________________________________
// function to induce variable scope for $ to jquery
function initJquery() {
	var	$ = jQuery;
	// checkUserName ________________________________________________________________
	// USED ON REGISTER PAGE AND BLOCK
/*	$(document).ready(function(){
		$("#registerform").find("#username").after('  <div id="userCheck"><a  id="checkUserName" href="#">' + localString('js_check_availability') +'</a><span id="yesOrNo"></span></div>');
		$("#checkUserName").click(function(e){
		    if(! $('#registerform').find('#username').val()) {

				$("#yesOrNo").html(localString('js_please_enter_username'));

			} else {
				$("#yesOrNo")
				// empty old value if there is one
				.empty()
				// append loading graphic  
				.append('<img src="/images/ajax-loader.gif" />')
				//make request
				.load("http://" + location.hostname + "/user/nameunique/" + encodeURI($("#username").val()) + "",  {submitMethod:"ajax"}, function(){
					$(this).hide().fadeIn();
				});
	
			}
			e.preventDefault();
		});
	});
	*/
	// HOME specific
	$(document).ready(function(){

		// prep check link
		$("#check_shortcode, #sign_up_btn").attr("href", "#TB_inline?height=350&width=525&inlineId=reg");
 
		// on click get text from banner and insert it into ThickBox form
		$("#check_shortcode, #sign_up_btn").click(function(){
			var userVal = $("#test_username").val();
			$("#home #registerform #username").attr("value", userVal);
		})
		
		// handle thickbox form submit
		$("#home #registerform").submit(function(){
			var emailVal = $(this).find("#email").val();
			$("#email2").attr("value", emailVal); 
		})
		
	
		// handle featured user iframe creation and toggling
		$("#home #main_banner").append('<iframe src="#"></iframe>');
		
		$("#home #main_banner #featured_users li a").each(function(index){
			if(index == 0) {
				$("#home #main_banner iframe").attr("src", $(this).attr("href"));
				$("#text_to .username").text($(this).find("span").text());
				$(this).parent().parent().addClass("selected");
			}
			$(this).click(function(e){
				$("#home #main_banner iframe").attr("src", $(this).attr("href"));
				$("#home #main_banner #featured_users li").removeClass("selected");
				$("#text_to .username").text($(this).text());
				$(this).parent().parent().addClass("selected");
				e.preventDefault();
			})
		})
		$("#launch_welcome").attr("href", "#TB_inline?height=400&width=905&inlineId=personalize").click();
	})
	
	//reg success
	$(document).ready(function(){
		$("#launch_success").attr("href", "#TB_inline?height=350&width=525&inlineId=reg_success&modal=true").click();
	})
//	#TB_inline?height=350&width=525&inlineId=reg


	// START THICKBOX OVERRIDE FUNTIONALITY ________________________________________________________________
	/*
	* SIMULATE CLICK TO RUN JS FORM
	*/
	$(document).ready(function(){
		$(".thickbox").click(function(){
			$("#checkUserName").click();
		});
	});

}
initJquery();

function showLoginOverlay()
{
	showdiv('overlay_signin');
	showdiv('signin_box');
	jumpCursor();
	fixOverlay();
	setElementValue('postLoginUrl',window.location.href);
}

function userLogin()
{
	var userNameElem = document.getElementById('username_head');
	var passwordElem = document.getElementById('password_head');
	if(userNameElem == null || passwordElem == null) 
		return;
	var url = '/user/loginajax/';
	var submitdata = "username=" + userNameElem.value + "&password="+passwordElem.value;
	new jQuery.ajax({url: url, type:'post', data:submitdata, success:userLoginSuccess, error:userLoginError});
	return false;
}

function userLoginSuccess(data)
{
	try
	{
		eval("var msg = " + data);

		if (null != msg.error)
		{
			// Error in Sign-In
			var errorElem = document.getElementById('overlayErrorMessage');
			errorElem.innerHTML = msg.error.message;
			showdiv('overlayErrorMessage');
		}
		else
		{
			// SUCCESS!!!
			hidediv('overlay_signin');hidediv('signin_box');hidediv('overlayErrorMessage');
			var postLoginUrlElem = document.getElementById('postLoginUrl');
			if(msg.redirectUrl != null){
				window.location.href = msg.redirectUrl; 
			}else if(postLoginUrlElem == null || postLoginUrlElem.value == null) {
				window.location.reload();
			}
			else {
				window.location.href = postLoginUrlElem.value.replace('USERNAMEHERE', msg.user);
			}
		}
	}
	catch(e)
	{		
	}
}

function userLoginError()
{
	var errorElem = document.getElementById('overlayErrorMessage');
	showdiv('overlayErrorMessage');
	errorElem.innerHTML = 'Currently we are facing some issues, please try again later.';

}

/**
 * All functions for Sharing via Email/SMS/Publish
 * @author Ram Hariharan
 */
var shareManager = {
	/** Initialize the share overlay */
	initpopup: function() {
		showdiv('overlay_signin');
		showdiv('share_box');
		fixOverlayHeight();
	},
	
	/** Popup the overlay with Share-By-Email selected */
	popupEmail: function(cids,publishtype) {
		shareManager.initpopup();
		hidediv ("email_collapsed");
		showdiv ("email_expand");
		showdiv ("share_email_form");
		showdiv ("share_email_action_buttons");
		hidediv ("share_email_status");
		hidediv ("share_email_override_buttons");
		frm = getValue('frm_promote_share_email');
		frm.share_with.value = ""; // Reset To
		frm.share_subject.value = localString('js_share_email_subject_default'); // Reset Subject
		frm.message.value = ""; // Reset Message
		frm.discard_invalid.value="";
		frm.cids.value=cids;
		
		frmSms = getValue('frm_promote_share_sms');
		if (frmSms){
		frmSms.share_with.value = ""; // Reset To
		frmSms.message.value = ""; // Reset Message
		frmSms.cids.value = cids; // sms
		frmSms.discard_invalid.value="";
		showdiv ("share_sms_form");
		showdiv ("share_sms_action_buttons");
		hidediv ("share_sms_status");
		hidediv ("share_sms_override_buttons");
		}
		getValue('publisherForm').cids.value = cids;		
		/* show the publishing pane but keep the publish pane collapsed*/
		showdiv ("publisher_pane");
		hidediv ("share_publish_status");
		// for status message publishing, we need to show some buttons and hide some
		displayButtons(publishtype);
		
	},
	
	/** Popup the overlay with Publish selected */
	popupPublish: function(cids,publishtype) {
		shareManager.initpopup();
		
		hidediv ("publish_collapsed");
		showdiv ("publish_expand");
		showdiv ("publisher_pane");
		showdiv ("share_publish_status");
		hidediv ("share_publish_status");
		frm = getValue('publisherForm');
		if( cids == null || cids == "" || cids.length <= 0) { 
			frm.cids.value = getValue('frm_promote_share_email').cids.value;
		}else {			
			getValue('frm_promote_share_email').cids.value = cids;
			getValue('frm_promote_share_sms').cids.value = cids;
			frm.cids.value=cids;
		}
		
		// for status message publishing, we need to show some buttons and hide some
		displayButtons(publishtype);
		// document.frm_promote_share_email.cids.value=cids;
	},
	
	/** Hide the share overlay */
	popdown: function() {
		shareManager.hide();
		hidediv('share_box');
		hidediv('overlay_signin');
		//multiSelect.setAll(false); // line commented for TT # 6639
		getValue('frm_promote_share_email').cids.value = "";
		getValue('publisherForm').cids.value = "";
	},

	/** Hide all the share sections */
	hide: function() {
		showdiv("email_collapsed");
		hidediv("email_expand");
		showdiv("publish_collapsed");
		hidediv("publish_expand");
	},
	
	/** The main call to SHARE-By-Email (uses Ajax to update server) */
	runShareEmail: function() {
		frm = getValue('frm_promote_share_email');
		statusDiv = getValue('share_email_status');
		
		showdiv ("share_email_status");
		
		url = '/promote/share';
		
		submitdata = "submitMethod=ajax"; 
        submitdata += "&share_type=email&share_with=" + frm.share_with.value ;
        submitdata += "&share_what=" + frm.cids.value + "&share_subject=" + frm.share_subject.value;
        submitdata += "&ignore_invalid=" + frm.discard_invalid.value + "&message=" + frm.message.value;
	 
        statusDiv.innerHTML = ' <img src="/images/common/indicator.gif" />';
        
        new jQuery.ajax({url: url, type: 'post', data: submitdata, 
				success: function(t){
					eval( 'var data = ' + t ); // decode json response
					if (null != data.error)
					{
						replaceClass('share_email_status', 'successColor', 'errorColor');
						// Error
						statusDiv.innerHTML = data.error.message;
						if (data.error.code != 98)
						{
							// Inputs are valid but the email-sending failed.
							// -- Show Discard buttons
							if (data.error.code != 99)
							{
								showdiv ('share_email_override_buttons');
							}							
							hidediv ("share_email_form");
							hidediv ("share_email_action_buttons");
						}
					}
					else
					{
						replaceClass('share_email_status', 'errorColor', 'successColor');
						// SUCCESS!!!
						statusDiv.innerHTML = data.response;
						hidediv ("share_email_form");
						hidediv ("share_email_action_buttons");
						hidediv ('share_email_override_buttons');
					}
				},
				error: function(t) {
					// Connection Error
					statusDiv.innerHTML = 'Internal Error';
				}
        });
     

	},
	// to share the statusMessage by Email
	runStatusShareEmail: function() {
		frm = getValue('frm_promote_share_email');
		statusDiv = getValue('share_email_status');
		
		showdiv ("share_email_status");
		
		url = '/promote/sharestatus';
		
		submitdata = "submitMethod=ajax"; 
        submitdata += "&share_type=email&share_with=" + frm.share_with.value ;
        submitdata += "&share_subject=" + frm.share_subject.value;
        submitdata += "&ignore_invalid=" + frm.discard_invalid.value + "&message=" + frm.message.value;
	 
        statusDiv.innerHTML = ' <img src="/images/common/indicator.gif" />';
        
        new jQuery.ajax({url: url, type: 'post', data: submitdata, 
				success: function(t){
					eval( 'var data = ' + t ); // decode json response
					if (null != data.error)
					{
						replaceClass('share_email_status', 'successColor', 'errorColor');
						// Error
						statusDiv.innerHTML = data.error.message;
						if (data.error.code != 98)
						{
							// Inputs are valid but the email-sending failed.
							// -- Show Discard buttons
							if (data.error.code != 99)
							{
								showdiv ('share_email_override_buttons');
							}							
							hidediv ("share_email_form");
							hidediv ("share_email_action_buttons");
						}
					}
					else
					{
						replaceClass('share_email_status', 'errorColor', 'successColor');
						// SUCCESS!!!
						statusDiv.innerHTML = data.response;
						hidediv ("share_email_form");
						hidediv ("share_email_action_buttons");
						hidediv ('share_email_override_buttons');
					}
				},
				error: function(t) {
					// Connection Error
					statusDiv.innerHTML = 'Internal Error';
				}
        });
     

	},
	
	/** The main call to SHARE-By-Sms (uses Ajax to update server) */
	runShareSms: function() {
		frm = getValue('frm_promote_share_sms');
		statusDiv = getValue('share_sms_status');
		
		showdiv ("share_sms_status");
		
		url = '/promote/share';
		
		submitdata = "submitMethod=ajax"; 
        submitdata += "&share_type=sms&share_with=" + URLEncode( frm.share_with.value );
        submitdata += "&share_what=" + frm.cids.value;
        submitdata += "&ignore_invalid=" + frm.discard_invalid.value + "&message=" + frm.message.value;
        
        statusDiv.innerHTML = ' <img src="/images/common/indicator.gif" />';
        
        new jQuery.ajax({url: url, type: 'post', data: submitdata, 
			success: function(t){
			eval( 'var data = ' + t ); // decode json response
			if (null != data.error)
			{
				replaceClass('share_sms_status', 'successColor', 'errorColor');
				// Error
				statusDiv.innerHTML = data.error.message;
				if (data.error.code != 98)
				{					
					// -- Show Discard buttons
					if (data.error.code != 99)
					{
						showdiv ('share_sms_override_buttons');
					}							
					hidediv ("share_sms_form");
					hidediv ("share_sms_action_buttons");
				}
			}
			else
			{
				replaceClass('share_sms_status', 'errorColor', 'successColor');
				// SUCCESS!!!
				statusDiv.innerHTML = data.response;
				hidediv ("share_sms_form");
				hidediv ("share_sms_action_buttons");
				hidediv ('share_sms_override_buttons');
			}
		},
		error: function(t) {
			// Connection Error
			statusDiv.innerHTML = 'Internal Error';
		}
    });

		
	},
	// to share status message by sms
	runStatusShareSms: function() {
		frm = getValue('frm_promote_share_sms');
		statusDiv = getValue('share_sms_status');
		
		showdiv ("share_sms_status");
		
		url = '/promote/sharestatus';
		
		submitdata = "submitMethod=ajax"; 
        submitdata += "&share_type=sms&share_with=" + URLEncode( frm.share_with.value );
        submitdata += "&ignore_invalid=" + frm.discard_invalid.value + "&message=" + frm.message.value;
        
        statusDiv.innerHTML = ' <img src="/images/common/indicator.gif" />';
        
        new jQuery.ajax({url: url, type: 'post', data: submitdata, 
			success: function(t){
			eval( 'var data = ' + t ); // decode json response
			if (null != data.error)
			{
				replaceClass('share_sms_status', 'successColor', 'errorColor');
				// Error
				statusDiv.innerHTML = data.error.message;
				if (data.error.code != 98)
				{					
					// -- Show Discard buttons
					if (data.error.code != 99)
					{
						showdiv ('share_sms_override_buttons');
					}							
					hidediv ("share_sms_form");
					hidediv ("share_sms_action_buttons");
				}
			}
			else
			{
				replaceClass('share_sms_status', 'errorColor', 'successColor');
				// SUCCESS!!!
				statusDiv.innerHTML = data.response;
				hidediv ("share_sms_form");
				hidediv ("share_sms_action_buttons");
				hidediv ('share_sms_override_buttons');
			}
		},
		error: function(t) {
			// Connection Error
			statusDiv.innerHTML = 'Internal Error';
		}
    });

		
	}
 }
function textAreaCounter(field, maxlimit)
{
	if (field.value.length > maxlimit) // if too long...trim it!
		field.value = field.value.substring(0, maxlimit);
}
function disableTabKey(evt)
{
   var charCode = (evt.which) ? evt.which : evt.keyCode;
   if (charCode == 9)
      return false;
   return true;
}
function setElementValue(elemId, elemValue)
{
	var elem = document.getElementById(elemId);
	if(elem == null || elem.value == null)
		return;
	elem.value = elemValue;

}
function  restrictMobileNumber(e, elem, plus)
{     
	try {
		var ch='';
		if((elem.value.length>0 && elem.value.charAt(0)=='+') && plus)
		{
			ch = '+';
		}
		var keyValue=Number(e);
		if(!((keyValue>47 && keyValue<58)||(keyValue>34 && keyValue<41))){	
	  		var num = ch + elem.value.replace(/[^\d]/g,"");        	
	   		elem.value = num;
	   	}
	} catch (e) {
	}
}
/*
*	This function is used to change the selected value of a drop downlist on the basis of text
*/
function changeSelection(obj, newValue) {
	for(i = 0 ; i < obj.length; i++) {			
		if(obj[i].text == newValue) {
			obj[i].selected = true; 
		}
	}
}


// ====================================================================
//       URLEncode and URLDecode functions
//
// Copyright Albion Research Ltd. 2002
// http://www.albionresearch.com/
//
// You may copy these functions providing that 
// (a) you leave this copyright notice intact, and 
// (b) if you use these functions on a publicly accessible
//     web site you include a credit somewhere on the web site 
//     with a link back to http://www.albionresearch.com/
//
// If you find or fix any bugs, please let us know at albionresearch.com
//
// SpecialThanks to Neelesh Thakur for being the first to
// report a bug in URLDecode() - now fixed 2003-02-19.
// And thanks to everyone else who has provided comments and suggestions.
// ====================================================================
function URLEncode( plaintext )
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for
	
	return encoded;
};

function URLDecode( encoded )
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
   return plaintext;
};

function displayButtons(publishtype)
{
	// for share and publish
	// here if publishtype is null or 0 , we show the media buttons. else we show the status buttons
	
	var mediaDisplay;
	var statusDisplay;
	
	if (!publishtype || publishtype == 0) // show the media buttons
	{
		mediaDisplay = "inline";
		statusDisplay = "none";
	}
	else // show the status buttons
	{
		mediaDisplay = "none";
		statusDisplay = "inline";
	}
	
	///// email buttons
	if (document.getElementById("share_email_statusbutton"))
	{
		document.getElementById("share_email_statusbutton").style.display = statusDisplay;
	}
	
	if (document.getElementById("share_email_mediabutton"))
	{
		document.getElementById("share_email_mediabutton").style.display = mediaDisplay;
	}
	
	///// sms buttons
	if (document.getElementById("share_sms_statusbutton"))
	{
		document.getElementById("share_sms_statusbutton").style.display = statusDisplay;
	}
	
	if (document.getElementById("share_sms_mediabutton"))
	{
		document.getElementById("share_sms_mediabutton").style.display = mediaDisplay;
	}
	
	//// publish buttons
	if (document.getElementById("publish_statusbutton"))
	{
		document.getElementById("publish_statusbutton").style.display = statusDisplay;
	}
	
	if (document.getElementById("publish_mediabutton"))
	{
		document.getElementById("publish_mediabutton").style.display = mediaDisplay;
	}
}

