//BROWSER DETECTION
var ns4 = document.layers;
var ns6 = document.getElementById && !document.all;
var ie4 = document.all;
function DetectBrowser(){ //Detectarea browserului folosit
	this.ver=navigator.appVersion
	this.agent=navigator.userAgent
	this.dom=document.getElementById?1:0
	this.opera5=(navigator.userAgent.indexOf("Opera")>-1 && document.getElementById)?1:0
	this.ie5=(this.ver.indexOf("MSIE 5")>-1 && this.dom && !this.opera5)?1:0; 
	this.ie6=(this.ver.indexOf("MSIE 6")>-1 && this.dom && !this.opera5)?1:0;
	this.ie4=(document.all && !this.dom && !this.opera5)?1:0;
	this.ie=this.ie4||this.ie5||this.ie6
	this.mac=this.agent.indexOf("Mac")>-1
	this.ns6=(this.dom && parseInt(this.ver) >= 5) ?1:0; 
	this.ns4=(document.layers && !this.dom)?1:0;
	this.bw=(this.ie6 || this.ie5 || this.ie4 || this.ns4 || this.ns6 || this.opera5)
	return this
}
var bw=new DetectBrowser();
//FIELDS
function imgField(field, img){
	//bgcolor
		if(img == "over"){
			//bgcolor = "#FFFFFF";
			border_color = "#CCCCCC";
		}else {
			//bgcolor = "#FFFBFF";
			border_color = "#E0E1E0";
		}
		field.style.borderColor = border_color;
		//field.style.backgroundColor = bgcolor;
}
//BUTS
function imgBut(but, img){
	but.src = img;
}
//Reset Form
function resetForm(formName){
	if(ns6) form = eval("document.getElementById('"+formName+"')");
	else if(ns4) form = eval("document."+formName);
	else form = eval("document.all."+formName);
	form.reset();
}
function focus2(field){
	if(field.value == 0) field.value = '';
}	
function blur2(field){
	if(field.value == '') field.value = '0';
}	
function fieldValue(field_name){
	if(ns6) field = eval("document.getElementById('"+field_name+"')");
	else if(ns4) field = eval("document."+field_name);
	else field = eval("document.all."+field_name);
	return field.value;
}
function setFieldValue(field_name, val){
	if(ns6) field = eval("document.getElementById('"+field_name+"')");
	else if(ns4) field = eval("document."+field_name);
	else field = eval("document.all."+field_name);
	return field.value;
	field.value = val;
}
function writeIn(field_name, val){
	if(ns6) field = eval("document.getElementById('"+field_name+"')");
	else if(ns4) field = eval("document."+field_name);
	else field = eval("document.all."+field_name);
	field.innerHTML = val;
}
function formatNR(nr, dec)
{
str = "" + Math.round(eval(nr) * Math.pow(10,dec));
while(str.length < dec)
	str = "0" + str;
decidx = str.length - dec;
tmp = str.substring(0,decidx);
if(tmp == '')
	tmp = '0';
if(dec > 0)
	tmp = tmp + '.' + str.substring(decidx, str.length);
return(tmp);
}
function getkey(e)
{
if (window.event)
   return window.event.keyCode;
else if (e)
   return e.which;
else
   return null;
}
function goodchars(e, goods)
{
var key, keychar;
key = getkey(e);
if (key == null) return true;
// get character
keychar = String.fromCharCode(key);
keychar = keychar.toLowerCase();
goods = goods.toLowerCase();
// check goodkeys
if (goods.indexOf(keychar) != -1)
	return true;
// control keys
if ( key==null || key==0 || key==8 || key==9 || key==13 || key==27 )
   return true;
// else return false
return false;
}
function getSelectedRadio(buttonGroup) {
   // returns the array number of the selected radio button or -1 if no button is selected
   if (buttonGroup[0]) { // if the button group is an array (one button is not an array)
      for (var i=0; i<buttonGroup.length; i++) {
         if (buttonGroup[i].checked) {
            return i
         }
      }
   } else {
      if (buttonGroup.checked) { return 0; } // if the one button is checked, return zero
   }
   // if we get to this point, no radio button is selected
   return -1;
} // Ends the "getSelectedRadio" function
function getSelectedRadioValue(buttonGroup) {
   // returns the value of the selected radio button or "" if no button is selected
   var i = getSelectedRadio(buttonGroup);
   if (i == -1) {
      return "";
   } else {
      if (buttonGroup[i]) { // Make sure the button group is an array (not just one button)
         return buttonGroup[i].value;
      } else { // The button group is just the one button, and it is checked
         return buttonGroup.value;
      }
   }
} // Ends the "getSelectedRadioValue" function
function getSelectedCheckbox(buttonGroup) {
   // Go through all the check boxes. return an array of all the ones
   // that are selected (their position numbers). if no boxes were checked,
   // returned array will be empty (length will be zero)
   var retArr = new Array();
   var lastElement = 0;
   if (buttonGroup[0]) { // if the button group is an array (one check box is not an array)
      for (var i=0; i<buttonGroup.length; i++) {
         if (buttonGroup[i].checked) {
            retArr.length = lastElement;
            retArr[lastElement] = i;
            lastElement++;
         }
      }
   } else { // There is only one check box (it's not an array)
      if (buttonGroup.checked) { // if the one check box is checked
         retArr.length = lastElement;
         retArr[lastElement] = 0; // return zero as the only array value
      }
   }
   return retArr;
} // Ends the "getSelectedCheckbox" function
function getSelectedCheckboxValue(buttonGroup) {
   // return an array of values selected in the check box group. if no boxes
   // were checked, returned array will be empty (length will be zero)
   var retArr = new Array(); // set up empty array for the return values
   var selectedItems = getSelectedCheckbox(buttonGroup);
   if (selectedItems.length != 0) { // if there was something selected
      retArr.length = selectedItems.length;
      for (var i=0; i<selectedItems.length; i++) {
         if (buttonGroup[selectedItems[i]]) { // Make sure it's an array
            retArr[i] = buttonGroup[selectedItems[i]].value;
         } else { // It's not an array (there's just one check box and it's selected)
            retArr[i] = buttonGroup.value;// return that value
         }
      }
   }
   return retArr;
} // Ends the "getSelectedCheckBoxValue" function
//Email Validation
function emailValid(email)
{
  var result = false
  var theStr = new String(email)
  var index = theStr.indexOf("@");
  if (index > 0)
  {
    var pindex = theStr.indexOf(".",index);
    if ((pindex > index+1) && (theStr.length > pindex+1))
	result = true;
  }
  return result;
}
function formSubmit(form, act){
	document.forms[form].action = act;
	document.forms[form].submit();
}
function fieldOb(field_name){
	if(ns6) field = eval("document.getElementById('"+field_name+"')");
	else if(ns4) field = eval("document."+field_name);
	else field = eval("document.all."+field_name);
	return field;
}
function changeRowColor(row, color){
	rOb = fieldOb(row);
	rOb.bgColor = color;  
}
function ValidEmail(form, field){
	elem = eval('form.' + field);
	if(elem.value != '')
		if (field.indexOf('email') != -1) {
			if (!emailValid(elem.value)) {
				alert('Invalid E-mail address !');
				elem.focus();
				return (false);
			}
		}
	return (true);
}
//Validates a field
function ValidateField(elem, name){
	if((elem.value == ''))	{ // ||(elem.value == 0)
    		alert('Warning: Not all mandatory fields have been filled!');
    		elem.focus();
   	 		return(false);
   	}
	else if(name.indexOf('email') != -1){
			 	if(!emailValid(elem.value)){
					alert('Invalid E-mail address !');
					elem.focus();
   	 				return(false);
				}
	}
	return(true);
}
//Just Validates a field without (alert & focus)
function JustValidateField(elem){
	if((elem.value == '')||(elem.value == 0))	return(false);
	else if(name.indexOf('email') != -1){
			 	if(!emailValid(elem.value)){
   	 				return(false);
				}
	}
	return(true);
}
//Validate form for Mandatory fields to be filled properly
function Validate(form, fields){
   	mandatory_fields = fields.split(',');
	for(i=0; i<mandatory_fields.length; i++){
		if(mandatory_fields[i].indexOf('|')){
			//groupped fields (at least one of them must be filled/selected)
			mandatory_group_fields = mandatory_fields[i].split('|');
			valid = 0;
			for(j=0; j<mandatory_group_fields.length; j++){
				elem = eval('form.' + mandatory_group_fields[j]);
				if(ValidateField(elem, mandatory_group_fields[j]) ) valid = 1;
				else return(false);
			}
			if(!valid){
				//no fields filled
				elem = eval('form.' + mandatory_group_fields[0]);
				if(!ValidateField(elem, mandatory_group_fields[0])) return(false);
			}
		}else{
			//single field
			elem = eval('form.' + mandatory_fields[i]);
			if(!ValidateField(elem, mandatory_fields[i])) return(false);
		}
	}//for
	return(true);
}
function OpenMRow(){
	ob = fieldOb('mand_nr');	
	if(ob != null){
		if(ob.value > 10){
			alert('You can add maximum 10 mandatory questions.');
			return false;
		}
		ob_field = fieldOb('row' + ob.value);	
		if(ob_field != null) ob_field.className = 'field_row';
		ob.value = parseInt(ob.value) + 1;
	}
}
function OpenORow(){
	ob = fieldOb('opt_nr');	
	if(ob != null){
		if(ob.value > 20){
			alert('You can add maximum 20 optional questions.');
			return false;
		}
		ob_field = fieldOb('row' + ob.value + 'o');	
		if(ob_field != null) ob_field.className = 'field_row';
		ob.value = parseInt(ob.value) + 1;
	}
}
function OpenPollRow(){
	ob = fieldOb('choicefields');	
	if(ob != null){
		if(ob.value > 300){
			alert('You can add maximum 300 choices.');
			return false;
		}
		ob_field = fieldOb('row' + ob.value);	
		if(ob_field != null) ob_field.className = 'field_row';
		ob.value = parseInt(ob.value) + 1;
	}
}
function OpenMembersRow(){
	ob = fieldOb('mfields');	
	if(ob != null){
		if(ob.value > 300){
			alert('You can add maximum 300 members.');
			return false;
		}
		ob_field = fieldOb('row' + ob.value);	
		if(ob_field != null) ob_field.className = 'field_row';
		ob.value = parseInt(ob.value) + 1;
	}
}
function FindScreenDim(type, div){
	ob = fieldOb(div);
	if(type == 'width') ob.style.width = screen.width + 'px';
	else if(type == 'height') ob.style.height = screen.height + 'px';
}
function OpenFacebook(){
	ob = fieldOb('open_facebook');
	ob.value = 1;
}
var gata = 0;
var oldlength = 0;
var maxlimit = 0;
var leftchars = 0;
var current = 0;
var ok = 1;
var msup = 0;
var key = 0;
var NEXT_PG = 0;
var PREV_PG = 0;
var $j = jQuery.noConflict();
$j(document).ready(function(){
	if ($j('img.photo_details').length > 0)
		$j('img.photo_details').cluetip({
			tracking:true
			,width:150
			,positionBy:'mouse'
			,dropShadow:false
			,attribute:'alt'
			,cluetipClass: 'jtip'
		});
	if ($j('#formPhotoComment').length > 0) {
		$j('#formPhotoComment').ajaxForm({
			success: function(response){
				if (response != 'success') {
					alert(response);
				}
				else {
					$j('#photocomments').load(HTTP + 'index.php?load_pic_comments=' + PIC_ID);
					$j('#formPhotoComment').clearForm();
				}
			}
		});
	}
	if($j('#formEdsel_photo').length > 0)
		$j('#formEdsel_photo').ajaxForm({success: function(response) {
				if (response != 'File successfully uploaded') {
					$j('#right_side').html(response);
					gata = 0;
				}
				else {
					gata = 1;
					self.parent.tb_remove();
					self.parent.document.location = 'index.php?user_photos=' + USERPROFILE_ID;
				}				
		}});
	$j('form#formQSet input[type=text]').keyup(function(e){		
		var text = $j(this).val();
		var textlength = text.length;
		if(textlength > 100){
			$j(this).val(text.substr(0,100));
			 return false;
		}else{
			return true;
		}
 	});
	$j('form#formText textarea').keyup(function(e){
		maxlimit = $j('#formleftchars').attr('value');
		all_text = '';
		$j('form#formText textarea').each(function(){
			all_text += $j(this).val();	
		});
		remaining_chars = maxlimit-all_text.length;
		if (remaining_chars < 0) {
			text_value = $j(this).val();
			$j(this).val(text_value.substr(0, text_value.length+remaining_chars));
			remaining_chars='0';
		}
		if(remaining_chars == 0)
			remaining_chars = '0';
		$j('span#charsleft').html(remaining_chars);
	});
	$j('form#formUserQ textarea').keyup(function(e){
		if ( ! include_textarea($j(this).attr('id'))) return;
		maxlimit = $j('#formleftchars').attr('value');
		all_text = '';
		$j('form#formUserQ textarea').filter(filter_textarea).each(function(){
			all_text += $j(this).val();	
		});
		remaining_chars = maxlimit-all_text.length;
		if (remaining_chars < 0) {
			text_value = $j(this).val();
			$j(this).val(text_value.substr(0, text_value.length+remaining_chars));
			remaining_chars='0';
		}
		if(remaining_chars == 0)
			remaining_chars = '0';
		$j('span#charsleft').html(remaining_chars);
	});
	$j('form#frmc textarea').keydown(function(e){		
		if (ok == 1) {
			oldlength = $j(this).val().length;
			ok = 0;			
			key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
		}
 	});
	$j('form#frmc textarea').keyup(function(e){
		//detect if the check box is checked
		var name = $j(this).attr('id');			
		tp = name.substr(9);
		docount = 0
		if ($j('#check_' + tp).val() != null) {
			if ($j('#check_' + tp).is(':checked')) 
				docount = 1;
		}else docount = 1;
		//detect shift
		key1 = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
		if (key != 9 && key1 != 16 && key == key1 && docount == 1) {	
			if(ok == 0) ok = 1;
			else ok = 0;
						
			maxlimit = $j('#maxlimit').attr('value');
			var totals = $j('#totalchars').attr('value');
			//actualizez numarul de caractere al formularului fara textarea curennt
			currentlength = $j(this).val().length;
			totals = totals - oldlength;
			limit = maxlimit - totals;
			leftchars = $j('span#charsleft').html();
			var text1 = $j(this).val();
		//	current = maxlimit - totals - currentlength;
			if(currentlength > limit){
				$j(this).val(text1.substr(0, limit));
				totals = totals + limit;
			}else{
				$j('span#charsleft').html(limit-currentlength);
				totals = totals + currentlength;
			}		
			
			$j('#totalchars').attr('value', totals);
		}else if(key == 9 && key1 != 16){
			oldlength = $j(this).val().length;
			ok = 0;
		}else if(key1 == 16){
			docount = 1;
		}
 	//	limitChars('', 20, 'charlimitinfo');
 	});
	
	 if ($j("#dob").length > 0) {
		$j("#dob").datepicker({
					changeFirstDay: false,
					dateFormat: 'dd/mm/yy',
					showOn: 'both',
					buttonImage: HTTP+'_layouts/images/calendar1.gif',
					buttonImageOnly: true,
					yearRange: '1930:2030',
					defaultDate: new Date ( "January 1, 1990" )
				});
		}
	 
	 if ($j("#deadline").length > 0) {
			$j("#deadline").datepicker({
						changeFirstDay: false,
						dateFormat: 'dd/mm/yy',
						showOn: 'both',
						buttonImage: HTTP+'_layouts/images/calendar1.gif',
						buttonImageOnly: true,
						yearRange: '1930:2030',
						defaultDate: new Date ()
					});
			}
});
function limitChars(){
	maxlimit = $j('#maxlimit').attr('value');
}
function keydownfnc(e){
	//alert('aici');
	if (e == null) {
		keycode = event.keyCode
	}
	else {
		keycode = e.which
	}
	
	if (keycode == 27) {
		tb_remove();
		document.onkeydown = keydownfnc;
	}
	else if (NEXT_PG != null){
		if (keycode == 39 && NEXT_PG != 0) {
			//alert('asd');
			MM_swapImage('right_arr', '', HTTP + '_layouts/images/arrow_right_blue.png', 1);
		}
		else if (keycode == 37 && PREV_PG != 0) {
			MM_swapImage('left_arr', '', HTTP + '_layouts/images/arrow_left_blue.png', 1);
		}
	}
};
function ViewNotifications(){
	$j('#read_notifications').slideToggle();		
	if($j('#view_notifications').html() == 'View all')
		$j('#view_notifications').html('View unread');
	else
		$j('#view_notifications').html('View all');		
}
function ReadNotifications(cond){	
	$j('#notifications').html('<img align="absmiddle" src="'+ HTTP +'_layouts/images/loading.gif" style="padding-left: 150px;"/>');
	$j.post(HTTP + 'read_notifications/'+cond, {}, function(response){	    			
		$j('#notifications').html(response);	    		
    });	
}

function CheckToDoList(id,section,status,book){		
	$j('#content_to_do_list').html('<img align="absmiddle" src="'+ HTTP +'_layouts/images/loading.gif" style="padding-left: 83px; padding-top: 70px;"/>');
	$j.post(HTTP + 'check_to_do_list/'+id+'/'+section+'/'+status+'/'+book, {}, function(response){    		
		$j('#content_to_do_list').html(response);			
    });	
	if(status == 1){
		$j.post(HTTP + 'check_lock_profile/'+id, {}, function(response){    		
			if(response == 'success'){					
				$j('#div_locked0').removeClass('hidden');
				$j('#div_locked0').addClass('to_do_list_lock_overlay');
			}			
	    });
	}
}

function LockProfile(value){
	if(value<2){
		$j.post(HTTP + 'lock_profile/'+value, {}, function(response){
			if(response == 'success'){
				if(value==0){					
					$j('#div_locked0').removeClass('hidden');
					$j('#div_locked0').addClass('to_do_list_lock_overlay');
					$j('#div_locked1').removeClass('to_do_list_lock');
					$j('#div_locked1').addClass('hidden');
				}else{
					$j('#div_locked1').removeClass('hidden');
					$j('#div_locked1').addClass('to_do_list_lock');
					$j('#div_locked0').removeClass('to_do_list_lock_overlay');
					$j('#div_locked0').addClass('hidden');
				}
			}
				
	    });
	}else{
		$j('#div_locked0').removeClass('to_do_list_lock_overlay');
		$j('#div_locked0').addClass('hidden');
	}
}
//================= mktree.js ==================================
//Author: Matt Kruse <matt@mattkruse.com>
//WWW: http://www.mattkruse.com/
//Automatically attach a listener to the window onload, to convert the trees
addEvent(window,"load",convertTrees);
//Utility function to add an event listener
function addEvent(o,e,f){
	if (o.addEventListener){ o.addEventListener(e,f,true); return true; }
	else if (o.attachEvent){ return o.attachEvent("on"+e,f); }
	else { return false; }
}
//utility function to set a global variable if it is not already set
function setDefault(name,val) {
	if (typeof(window[name])=="undefined" || window[name]==null) {
		window[name]=val;
	}
}
//Full expands a tree with a given ID
function expandTree(treeId) {
	var ul = document.getElementById(treeId);
	if (ul == null) { return false; }
	expandCollapseList(ul,nodeOpenClass);
}
//Fully collapses a tree with a given ID
function collapseTree(treeId) {
	var ul = document.getElementById(treeId);
	if (ul == null) { return false; }
	expandCollapseList(ul,nodeClosedClass);
}
//Expands enough nodes to expose an LI with a given ID
function expandToItem(treeId,itemId) {
	var ul = document.getElementById(treeId);
	if (ul == null) { return false; }
	var ret = expandCollapseList(ul,nodeOpenClass,itemId);
	if (ret) {
		var o = document.getElementById(itemId);
		if (o.scrollIntoView) {
			o.scrollIntoView(false);
		}
	}
}
//Performs 3 functions:
//a) Expand all nodes
//b) Collapse all nodes
//c) Expand all nodes to reach a certain ID
function expandCollapseList(ul,cName,itemId) {
	if (!ul.childNodes || ul.childNodes.length==0) { return false; }
	// Iterate LIs
	for (var itemi=0;itemi<ul.childNodes.length;itemi++) {
		var item = ul.childNodes[itemi];
		if (itemId!=null && item.id==itemId) { return true; }
		if (item.nodeName == "LI") {
			// Iterate things in this LI
			var subLists = false;
			for (var sitemi=0;sitemi<item.childNodes.length;sitemi++) {
				var sitem = item.childNodes[sitemi];
				if (sitem.nodeName=="UL") {
					subLists = true;
					var ret = expandCollapseList(sitem,cName,itemId);
					if (itemId!=null && ret) {
						item.className=cName;
						return true;
					}
				}
			}
			if (subLists && itemId==null) {
				item.className = cName;
			}
		}
	}
}
//Search the document for UL elements with the correct CLASS name, then process them
function convertTrees() {
	setDefault("treeClass","mktree");
	setDefault("nodeClosedClass","liClosed");
	setDefault("nodeOpenClass","liOpen");
	setDefault("nodeBulletClass","liBullet");
	setDefault("nodeLinkClass","bullet");
	setDefault("preProcessTrees",true);
	if (preProcessTrees) {
		if (!document.createElement) { return; } // Without createElement, we can't do anything
		uls = document.getElementsByTagName("ul");
		for (var uli=0;uli<uls.length;uli++) {
			var ul=uls[uli];
			if (ul.nodeName=="UL" && ul.className==treeClass) {
				processList(ul);
			}
		}
	}
}
//Process a UL tag and all its children, to convert to a tree
function processList(ul) {
	if (!ul.childNodes || ul.childNodes.length==0) { return; }
	// Iterate LIs
	for (var itemi=0;itemi<ul.childNodes.length;itemi++) {
		var item = ul.childNodes[itemi];
		if (item.nodeName == "LI") {
			// Iterate things in this LI
			var subLists = false;
			for (var sitemi=0;sitemi<item.childNodes.length;sitemi++) {
				var sitem = item.childNodes[sitemi];
				if (sitem.nodeName=="UL") {
					subLists = true;
					processList(sitem);
				}
			}
			var s= document.createElement("SPAN");
			var t= '\u00A0'; // &nbsp;
			s.className = nodeLinkClass;
			if (subLists) {
				// This LI has UL's in it, so it's a +/- node
				if (item.className==null || item.className=="") {
					item.className = nodeClosedClass;
				}
				// If it's just text, make the text work as the link also
				if (item.firstChild.nodeName=="#text") {
					t = t+item.firstChild.nodeValue;
					item.removeChild(item.firstChild);
				}
				s.onclick = function () {
					this.parentNode.className = (this.parentNode.className==nodeOpenClass) ? nodeClosedClass : nodeOpenClass;
					return false;
				}
			}
			else {
				// No sublists, so it's just a bullet node
				item.className = nodeBulletClass;
				s.onclick = function () { return false; }
			}
			s.appendChild(document.createTextNode(t));
			item.insertBefore(s,item.firstChild);
		}
	}
}
// ========= end of mktree.js ==============================
/**
*
* Color picker
* Author: Stefan Petre www.eyecon.ro
* 
* Dual licensed under the MIT and GPL licenses
* 
*/
(function ($) {
	var ColorPicker = function () {
		var
			ids = {},
			inAction,
			charMin = 65,
			visible,
			tpl = '<div class="colorpicker"><div class="colorpicker_color"><div><div></div></div></div><div class="colorpicker_hue"><div></div></div><div class="colorpicker_new_color"></div><div class="colorpicker_current_color"></div><div class="colorpicker_hex"><input type="text" maxlength="6" size="6" /></div><div class="colorpicker_rgb_r colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_g colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_h colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_s colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_submit"></div></div>',
			defaults = {
				eventName: 'click',
				onShow: function () {},
				onBeforeShow: function(){},
				onHide: function () {},
				onChange: function () {},
				onSubmit: function () {},
				color: 'ff0000',
				livePreview: true,
				flat: false
			},
			fillRGBFields = function  (hsb, cal) {
				var rgb = HSBToRGB(hsb);
				$(cal).data('colorpicker').fields
					.eq(1).val(rgb.r).end()
					.eq(2).val(rgb.g).end()
					.eq(3).val(rgb.b).end();
			},
			fillHSBFields = function  (hsb, cal) {
				$(cal).data('colorpicker').fields
					.eq(4).val(hsb.h).end()
					.eq(5).val(hsb.s).end()
					.eq(6).val(hsb.b).end();
			},
			fillHexFields = function (hsb, cal) {
				$(cal).data('colorpicker').fields
					.eq(0).val(HSBToHex(hsb)).end();
			},
			setSelector = function (hsb, cal) {
				$(cal).data('colorpicker').selector.css('backgroundColor', '#' + HSBToHex({h: hsb.h, s: 100, b: 100}));
				$(cal).data('colorpicker').selectorIndic.css({
					left: parseInt(150 * hsb.s/100, 10),
					top: parseInt(150 * (100-hsb.b)/100, 10)
				});
			},
			setHue = function (hsb, cal) {
				$(cal).data('colorpicker').hue.css('top', parseInt(150 - 150 * hsb.h/360, 10));
			},
			setCurrentColor = function (hsb, cal) {
				$(cal).data('colorpicker').currentColor.css('backgroundColor', '#' + HSBToHex(hsb));
			},
			setNewColor = function (hsb, cal) {
				$(cal).data('colorpicker').newColor.css('backgroundColor', '#' + HSBToHex(hsb));
			},
			keyDown = function (ev) {
				var pressedKey = ev.charCode || ev.keyCode || -1;
				if ((pressedKey > charMin && pressedKey <= 90) || pressedKey == 32) {
					return false;
				}
				var cal = $(this).parent().parent();
				if (cal.data('colorpicker').livePreview === true) {
					change.apply(this);
				}
			},
			change = function (ev) {
				var cal = $(this).parent().parent(), col;
				if (this.parentNode.className.indexOf('_hex') > 0) {
					cal.data('colorpicker').color = col = HexToHSB(fixHex(this.value));
				} else if (this.parentNode.className.indexOf('_hsb') > 0) {
					cal.data('colorpicker').color = col = fixHSB({
						h: parseInt(cal.data('colorpicker').fields.eq(4).val(), 10),
						s: parseInt(cal.data('colorpicker').fields.eq(5).val(), 10),
						b: parseInt(cal.data('colorpicker').fields.eq(6).val(), 10)
					});
				} else {
					cal.data('colorpicker').color = col = RGBToHSB(fixRGB({
						r: parseInt(cal.data('colorpicker').fields.eq(1).val(), 10),
						g: parseInt(cal.data('colorpicker').fields.eq(2).val(), 10),
						b: parseInt(cal.data('colorpicker').fields.eq(3).val(), 10)
					}));
				}
				if (ev) {
					fillRGBFields(col, cal.get(0));
					fillHexFields(col, cal.get(0));
					fillHSBFields(col, cal.get(0));
				}
				setSelector(col, cal.get(0));
				setHue(col, cal.get(0));
				setNewColor(col, cal.get(0));
				cal.data('colorpicker').onChange.apply(cal, [col, HSBToHex(col), HSBToRGB(col)]);
			},
			blur = function (ev) {
				var cal = $(this).parent().parent();
				cal.data('colorpicker').fields.parent().removeClass('colorpicker_focus');
			},
			focus = function () {
				charMin = this.parentNode.className.indexOf('_hex') > 0 ? 70 : 65;
				$(this).parent().parent().data('colorpicker').fields.parent().removeClass('colorpicker_focus');
				$(this).parent().addClass('colorpicker_focus');
			},
			downIncrement = function (ev) {
				var field = $(this).parent().find('input').focus();
				var current = {
					el: $(this).parent().addClass('colorpicker_slider'),
					max: this.parentNode.className.indexOf('_hsb_h') > 0 ? 360 : (this.parentNode.className.indexOf('_hsb') > 0 ? 100 : 255),
					y: ev.pageY,
					field: field,
					val: parseInt(field.val(), 10),
					preview: $(this).parent().parent().data('colorpicker').livePreview					
				};
				$(document).bind('mouseup', current, upIncrement);
				$(document).bind('mousemove', current, moveIncrement);
			},
			moveIncrement = function (ev) {
				ev.data.field.val(Math.max(0, Math.min(ev.data.max, parseInt(ev.data.val + ev.pageY - ev.data.y, 10))));
				if (ev.data.preview) {
					change.apply(ev.data.field.get(0), [true]);
				}
				return false;
			},
			upIncrement = function (ev) {
				change.apply(ev.data.field.get(0), [true]);
				ev.data.el.removeClass('colorpicker_slider').find('input').focus();
				$(document).unbind('mouseup', upIncrement);
				$(document).unbind('mousemove', moveIncrement);
				return false;
			},
			downHue = function (ev) {
				var current = {
					cal: $(this).parent(),
					y: $(this).offset().top
				};
				current.preview = current.cal.data('colorpicker').livePreview;
				$(document).bind('mouseup', current, upHue);
				$(document).bind('mousemove', current, moveHue);
			},
			moveHue = function (ev) {
				change.apply(
					ev.data.cal.data('colorpicker')
						.fields
						.eq(4)
						.val(parseInt(360*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.y))))/150, 10))
						.get(0),
					[ev.data.preview]
				);
				return false;
			},
			upHue = function (ev) {
				fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
				fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
				$(document).unbind('mouseup', upHue);
				$(document).unbind('mousemove', moveHue);
				return false;
			},
			downSelector = function (ev) {
				var current = {
					cal: $(this).parent(),
					pos: $(this).offset()
				};
				current.preview = current.cal.data('colorpicker').livePreview;
				$(document).bind('mouseup', current, upSelector);
				$(document).bind('mousemove', current, moveSelector);
			},
			moveSelector = function (ev) {
				change.apply(
					ev.data.cal.data('colorpicker')
						.fields
						.eq(6)
						.val(parseInt(100*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.pos.top))))/150, 10))
						.end()
						.eq(5)
						.val(parseInt(100*(Math.max(0,Math.min(150,(ev.pageX - ev.data.pos.left))))/150, 10))
						.get(0),
					[ev.data.preview]
				);
				return false;
			},
			upSelector = function (ev) {
				fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
				fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
				$(document).unbind('mouseup', upSelector);
				$(document).unbind('mousemove', moveSelector);
				return false;
			},
			enterSubmit = function (ev) {
				$(this).addClass('colorpicker_focus');
			},
			leaveSubmit = function (ev) {
				$(this).removeClass('colorpicker_focus');
			},
			clickSubmit = function (ev) {
				var cal = $(this).parent();
				var col = cal.data('colorpicker').color;
				cal.data('colorpicker').origColor = col;
				setCurrentColor(col, cal.get(0));
				cal.data('colorpicker').onSubmit(col, HSBToHex(col), HSBToRGB(col), cal.data('colorpicker').el);
			},
			show = function (ev) {
				var cal = $('#' + $(this).data('colorpickerId'));
				cal.data('colorpicker').onBeforeShow.apply(this, [cal.get(0)]);
				var pos = $(this).offset();
				var viewPort = getViewport();
				var top = pos.top + this.offsetHeight;
				var left = pos.left;
				if (top + 176 > viewPort.t + viewPort.h) {
					top -= this.offsetHeight + 176;
				}
				if (left + 356 > viewPort.l + viewPort.w) {
					left -= 356;
				}
				cal.css({left: left + 'px', top: top + 'px'});
				if (cal.data('colorpicker').onShow.apply(this, [cal.get(0)]) != false) {
					cal.show();
				}
				$(document).bind('mousedown', {cal: cal}, hide);
				return false;
			},
			hide = function (ev) {
				if (!isChildOf(ev.data.cal.get(0), ev.target, ev.data.cal.get(0))) {
					if (ev.data.cal.data('colorpicker').onHide.apply(this, [ev.data.cal.get(0)]) != false) {
						ev.data.cal.hide();
					}
					$(document).unbind('mousedown', hide);
				}
			},
			isChildOf = function(parentEl, el, container) {
				if (parentEl == el) {
					return true;
				}
				if (parentEl.contains) {
					return parentEl.contains(el);
				}
				if ( parentEl.compareDocumentPosition ) {
					return !!(parentEl.compareDocumentPosition(el) & 16);
				}
				var prEl = el.parentNode;
				while(prEl && prEl != container) {
					if (prEl == parentEl)
						return true;
					prEl = prEl.parentNode;
				}
				return false;
			},
			getViewport = function () {
				var m = document.compatMode == 'CSS1Compat';
				return {
					l : window.pageXOffset || (m ? document.documentElement.scrollLeft : document.body.scrollLeft),
					t : window.pageYOffset || (m ? document.documentElement.scrollTop : document.body.scrollTop),
					w : window.innerWidth || (m ? document.documentElement.clientWidth : document.body.clientWidth),
					h : window.innerHeight || (m ? document.documentElement.clientHeight : document.body.clientHeight)
				};
			},
			fixHSB = function (hsb) {
				return {
					h: Math.min(360, Math.max(0, hsb.h)),
					s: Math.min(100, Math.max(0, hsb.s)),
					b: Math.min(100, Math.max(0, hsb.b))
				};
			}, 
			fixRGB = function (rgb) {
				return {
					r: Math.min(255, Math.max(0, rgb.r)),
					g: Math.min(255, Math.max(0, rgb.g)),
					b: Math.min(255, Math.max(0, rgb.b))
				};
			},
			fixHex = function (hex) {
				var len = 6 - hex.length;
				if (len > 0) {
					var o = [];
					for (var i=0; i<len; i++) {
						o.push('0');
					}
					o.push(hex);
					hex = o.join('');
				}
				return hex;
			}, 
			HexToRGB = function (hex) {
				var hex = parseInt(((hex.indexOf('#') > -1) ? hex.substring(1) : hex), 16);
				return {r: hex >> 16, g: (hex & 0x00FF00) >> 8, b: (hex & 0x0000FF)};
			},
			HexToHSB = function (hex) {
				return RGBToHSB(HexToRGB(hex));
			},
			RGBToHSB = function (rgb) {
				var hsb = {
					h: 0,
					s: 0,
					b: 0
				};
				var min = Math.min(rgb.r, rgb.g, rgb.b);
				var max = Math.max(rgb.r, rgb.g, rgb.b);
				var delta = max - min;
				hsb.b = max;
				if (max != 0) {
					
				}
				hsb.s = max != 0 ? 255 * delta / max : 0;
				if (hsb.s != 0) {
					if (rgb.r == max) {
						hsb.h = (rgb.g - rgb.b) / delta;
					} else if (rgb.g == max) {
						hsb.h = 2 + (rgb.b - rgb.r) / delta;
					} else {
						hsb.h = 4 + (rgb.r - rgb.g) / delta;
					}
				} else {
					hsb.h = -1;
				}
				hsb.h *= 60;
				if (hsb.h < 0) {
					hsb.h += 360;
				}
				hsb.s *= 100/255;
				hsb.b *= 100/255;
				return hsb;
			},
			HSBToRGB = function (hsb) {
				var rgb = {};
				var h = Math.round(hsb.h);
				var s = Math.round(hsb.s*255/100);
				var v = Math.round(hsb.b*255/100);
				if(s == 0) {
					rgb.r = rgb.g = rgb.b = v;
				} else {
					var t1 = v;
					var t2 = (255-s)*v/255;
					var t3 = (t1-t2)*(h%60)/60;
					if(h==360) h = 0;
					if(h<60) {rgb.r=t1;	rgb.b=t2; rgb.g=t2+t3}
					else if(h<120) {rgb.g=t1; rgb.b=t2;	rgb.r=t1-t3}
					else if(h<180) {rgb.g=t1; rgb.r=t2;	rgb.b=t2+t3}
					else if(h<240) {rgb.b=t1; rgb.r=t2;	rgb.g=t1-t3}
					else if(h<300) {rgb.b=t1; rgb.g=t2;	rgb.r=t2+t3}
					else if(h<360) {rgb.r=t1; rgb.g=t2;	rgb.b=t1-t3}
					else {rgb.r=0; rgb.g=0;	rgb.b=0}
				}
				return {r:Math.round(rgb.r), g:Math.round(rgb.g), b:Math.round(rgb.b)};
			},
			RGBToHex = function (rgb) {
				var hex = [
					rgb.r.toString(16),
					rgb.g.toString(16),
					rgb.b.toString(16)
				];
				$.each(hex, function (nr, val) {
					if (val.length == 1) {
						hex[nr] = '0' + val;
					}
				});
				return hex.join('');
			},
			HSBToHex = function (hsb) {
				return RGBToHex(HSBToRGB(hsb));
			},
			restoreOriginal = function () {
				var cal = $(this).parent();
				var col = cal.data('colorpicker').origColor;
				cal.data('colorpicker').color = col;
				fillRGBFields(col, cal.get(0));
				fillHexFields(col, cal.get(0));
				fillHSBFields(col, cal.get(0));
				setSelector(col, cal.get(0));
				setHue(col, cal.get(0));
				setNewColor(col, cal.get(0));
			};
		return {
			init: function (opt) {
				opt = $.extend({}, defaults, opt||{});
				if (typeof opt.color == 'string') {
					opt.color = HexToHSB(opt.color);
				} else if (opt.color.r != undefined && opt.color.g != undefined && opt.color.b != undefined) {
					opt.color = RGBToHSB(opt.color);
				} else if (opt.color.h != undefined && opt.color.s != undefined && opt.color.b != undefined) {
					opt.color = fixHSB(opt.color);
				} else {
					return this;
				}
				return this.each(function () {
					if (!$(this).data('colorpickerId')) {
						var options = $.extend({}, opt);
						options.origColor = opt.color;
						var id = 'collorpicker_' + parseInt(Math.random() * 1000);
						$(this).data('colorpickerId', id);
						var cal = $(tpl).attr('id', id);
						if (options.flat) {
							cal.appendTo(this).show();
						} else {
							cal.appendTo(document.body);
						}
						options.fields = cal
											.find('input')
												.bind('keyup', keyDown)
												.bind('change', change)
												.bind('blur', blur)
												.bind('focus', focus);
						cal
							.find('span').bind('mousedown', downIncrement).end()
							.find('>div.colorpicker_current_color').bind('click', restoreOriginal);
						options.selector = cal.find('div.colorpicker_color').bind('mousedown', downSelector);
						options.selectorIndic = options.selector.find('div div');
						options.el = this;
						options.hue = cal.find('div.colorpicker_hue div');
						cal.find('div.colorpicker_hue').bind('mousedown', downHue);
						options.newColor = cal.find('div.colorpicker_new_color');
						options.currentColor = cal.find('div.colorpicker_current_color');
						cal.data('colorpicker', options);
						cal.find('div.colorpicker_submit')
							.bind('mouseenter', enterSubmit)
							.bind('mouseleave', leaveSubmit)
							.bind('click', clickSubmit);
						fillRGBFields(options.color, cal.get(0));
						fillHSBFields(options.color, cal.get(0));
						fillHexFields(options.color, cal.get(0));
						setHue(options.color, cal.get(0));
						setSelector(options.color, cal.get(0));
						setCurrentColor(options.color, cal.get(0));
						setNewColor(options.color, cal.get(0));
						if (options.flat) {
							cal.css({
								position: 'relative',
								display: 'block'
							});
						} else {
							$(this).bind(options.eventName, show);
						}
					}
				});
			},
			showPicker: function() {
				return this.each( function () {
					if ($(this).data('colorpickerId')) {
						show.apply(this);
					}
				});
			},
			hidePicker: function() {
				return this.each( function () {
					if ($(this).data('colorpickerId')) {
						$('#' + $(this).data('colorpickerId')).hide();
					}
				});
			},
			setColor: function(col) {
				if (typeof col == 'string') {
					col = HexToHSB(col);
				} else if (col.r != undefined && col.g != undefined && col.b != undefined) {
					col = RGBToHSB(col);
				} else if (col.h != undefined && col.s != undefined && col.b != undefined) {
					col = fixHSB(col);
				} else {
					return this;
				}
				return this.each(function(){
					if ($(this).data('colorpickerId')) {
						var cal = $('#' + $(this).data('colorpickerId'));
						cal.data('colorpicker').color = col;
						cal.data('colorpicker').origColor = col;
						fillRGBFields(col, cal.get(0));
						fillHSBFields(col, cal.get(0));
						fillHexFields(col, cal.get(0));
						setHue(col, cal.get(0));
						setSelector(col, cal.get(0));
						setCurrentColor(col, cal.get(0));
						setNewColor(col, cal.get(0));
					}
				});
			}
		};
	}();
	$.fn.extend({
		ColorPicker: ColorPicker.init,
		ColorPickerHide: ColorPicker.hidePicker,
		ColorPickerShow: ColorPicker.showPicker,
		ColorPickerSetColor: ColorPicker.setColor
	});
})(jQuery)
/*
 * JTip
 * By Cody Lindley (http://www.codylindley.com)
 * Under an Attribution, Share Alike License
 * JTip is built on top of the very light weight jquery library.
 */
//on page load (as soon as its ready) call JT_init
$j(document).ready(JT_init);
function JT_init(){
	       $j("a.jTip")
		   .hover(function(){JT_show(this.href,this.id,this.name)},function(){$j('#JT').remove()})
           .click(function(){return false});	   
}
function JT_show(url,linkId,title){
	if(title == false)title="&nbsp;";
	var de = document.documentElement;
	var w = self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var hasArea = w - getAbsoluteLeft(linkId);
	var clickElementy = getAbsoluteTop(linkId) - 3; //set y position	
	var queryString = url.replace(/^[^\?]+\??/,'');
	var params = parseQuery( queryString );
	if(params['width'] === undefined){params['width'] = 250};
	if(params['link'] !== undefined){
	$j('#' + linkId).bind('click',function(){window.location = params['link']});
	$j('#' + linkId).css('cursor','pointer');
	}
	if(hasArea>((params['width']*1)+75)){
		$j("body").append("<div id='JT' style='width:"+params['width']*1+"px'><div id='JT_close_left'>"+title+"</div><div id='JT_copy'><div class='JT_loader'><div></div></div>");//right side
		var arrowOffset = getElementWidth(linkId) + 11;
		var clickElementx = getAbsoluteLeft(linkId) + arrowOffset; //set x position
		$j('#JT_arrow_left').css({left: (clickElementx - 10) + "px", top: clickElementy +"px"});
	}else{
		$j("body").append("<div id='JT' style='width:"+params['width']*1+"px'><div id='JT_close_right'>"+title+"</div><div id='JT_copy'><div class='JT_loader'><div></div></div>");//left side
		var clickElementx = getAbsoluteLeft(linkId) - ((params['width']*1) + 15); //set x position
		$j('#JT_arrow_right').css({left: (getAbsoluteLeft(linkId) - 20) + "px", top: clickElementy + "px"});
	}
	$j('#JT').css({left: clickElementx+"px", top: clickElementy+"px"});
	$j('#JT_copy').load(url, function() {
	  //if jtip goes to left side and is partially cut off at left of doc...	  
	  if ($j('#JT_arrow_right') && clickElementx < 0) {
	    var JT_width = (getAbsoluteLeft(linkId) - 22);
	    $j('#JT').css({left: 2, width: JT_width}); //adjust width to fit
	  }
	  //get the height of the jtip after loading it
	  var jtip_height = $j('#JT').height();
	  //adjust the top of jTip
	  move_jtip();
	  if ( (scroll_position + window_height) - clickElementy < jtip_height ) {
	    var adjusted_top = (window_height - jtip_height) - 6 + scroll_position;
      if ( adjusted_top - scroll_position < 0 ) {
        $j('#JT').css({top: scroll_position + 1});
      } else {
        $j('#JT').css({top: adjusted_top});
      }
    }      
	});
	$j('#JT').show();

}
function getElementWidth(objectId) {
	x = document.getElementById(objectId);
	return x.offsetWidth;
}
function getAbsoluteLeft(objectId) {
	// Get an object left position from the upper left viewport corner
	o = document.getElementById(objectId)
	oLeft = o.offsetLeft            // Get left position from the parent object
	while(o.offsetParent!=null) {   // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent    // Get parent object reference
		oLeft += oParent.offsetLeft // Add parent left position
		o = oParent
	}
	return oLeft
}
function getAbsoluteTop(objectId) {
	// Get an object top position from the upper left viewport corner
	o = document.getElementById(objectId)
	oTop = o.offsetTop            // Get top position from the parent object
	while(o.offsetParent!=null) { // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent  // Get parent object reference
		oTop += oParent.offsetTop // Add parent top position
		o = oParent
	}
	return oTop
}
function parseQuery ( query ) {
   var Params = new Object ();
   if ( ! query ) return Params; // return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) continue;
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}
function move_jtip() {
  if (window.innerHeight) {
	  scroll_position = window.pageYOffset;
	  window_height = window.innerHeight;
	}
	else if (document.documentElement && document.documentElement.scrollTop) {
		scroll_position = document.documentElement.scrollTop;
    window_height = document.documentElement.clientHeight;
	}
	else if (document.body) {
	  scroll_position = document.body.scrollTop;
	  window_height = document.body.clientHeight;
	}
}
function blockEvents(evt) {
	if(evt.target){
		evt.preventDefault();
	}else{
		evt.returnValue = false;
	}
}
/**
 * jCarousel - Riding carousels with jQuery
 *   http://sorgalla.com/jcarousel/
 *
 * Copyright (c) 2006 Jan Sorgalla (http://sorgalla.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * Built on top of the jQuery library
 *   http://jquery.com
 *
 * Inspired by the "Carousel Component" by Bill Scott
 *   http://billwscott.com/carousel/
 */
(function($) {
    /**
     * Creates a carousel for all matched elements.
     *
     * @example $("#mycarousel").jcarousel();
     * @before <ul id="mycarousel" class="jcarousel-skin-name"><li>First item</li><li>Second item</li></ul>
     * @result
     *
     * <div class="jcarousel-skin-name">
     *   <div class="jcarousel-container">
     *     <div disabled="disabled" class="jcarousel-prev jcarousel-prev-disabled"></div>
     *     <div class="jcarousel-next"></div>
     *     <div class="jcarousel-clip">
     *       <ul class="jcarousel-list">
     *         <li class="jcarousel-item-1">First item</li>
     *         <li class="jcarousel-item-2">Second item</li>
     *       </ul>
     *     </div>
     *   </div>
     * </div>
     *
     * @name jcarousel
     * @type jQuery
     * @param Hash o A set of key/value pairs to set as configuration properties.
     * @cat Plugins/jCarousel
     */
    $.fn.jcarousel = function(o) {
        return this.each(function() {
            new $jc(this, o);
        });
    };

    // Default configuration properties.
    var defaults = {
        vertical: false,
        start: 1,
        offset: 1,
        size: null,
        scroll: 3,
        visible: null,
        animation: 'normal',
        easing: 'swing',
        auto: 0,
        wrap: null,
        initCallback: null,
        reloadCallback: null,
        itemLoadCallback: null,
        itemFirstInCallback: null,
        itemFirstOutCallback: null,
        itemLastInCallback: null,
        itemLastOutCallback: null,
        itemVisibleInCallback: null,
        itemVisibleOutCallback: null,
        buttonNextHTML: '<div></div>',
        buttonPrevHTML: '<div></div>',
        buttonNextEvent: 'click',
        buttonPrevEvent: 'click',
        buttonNextCallback: null,
        buttonPrevCallback: null
    };

    /**
     * The jCarousel object.
     *
     * @constructor
     * @name $.jcarousel
     * @param Object e The element to create the carousel for.
     * @param Hash o A set of key/value pairs to set as configuration properties.
     * @cat Plugins/jCarousel
     */
    $.jcarousel = function(e, o) {
        this.options    = $.extend({}, defaults, o || {});

        this.locked     = false;

        this.container  = null;
        this.clip       = null;
        this.list       = null;
        this.buttonNext = null;
        this.buttonPrev = null;

        this.wh = !this.options.vertical ? 'width' : 'height';
        this.lt = !this.options.vertical ? 'left' : 'top';

        // Extract skin class
        var skin = '', split = e.className.split(' ');

        for (var i = 0; i < split.length; i++) {
            if (split[i].indexOf('jcarousel-skin') != -1) {
                $(e).removeClass(split[i]);
                var skin = split[i];
                break;
            }
        }

        if (e.nodeName == 'UL' || e.nodeName == 'OL') {
            this.list = $(e);
            this.container = this.list.parent();

            if (this.container.hasClass('jcarousel-clip')) {
                if (!this.container.parent().hasClass('jcarousel-container'))
                    this.container = this.container.wrap('<div></div>');

                this.container = this.container.parent();
            } else if (!this.container.hasClass('jcarousel-container'))
                this.container = this.list.wrap('<div></div>').parent();
        } else {
            this.container = $(e);
            this.list = $(e).find('>ul,>ol,div>ul,div>ol');
        }

        if (skin != '' && this.container.parent()[0].className.indexOf('jcarousel-skin') == -1)
        	this.container.wrap('<div class=" '+ skin + '"></div>');

        this.clip = this.list.parent();

        if (!this.clip.length || !this.clip.hasClass('jcarousel-clip'))
            this.clip = this.list.wrap('<div></div>').parent();

        this.buttonPrev = $('.jcarousel-prev', this.container);

        if (this.buttonPrev.size() == 0 && this.options.buttonPrevHTML != null)
            this.buttonPrev = this.clip.before(this.options.buttonPrevHTML).prev();

        this.buttonPrev.addClass(this.className('jcarousel-prev'));

        this.buttonNext = $('.jcarousel-next', this.container);

        if (this.buttonNext.size() == 0 && this.options.buttonNextHTML != null)
            this.buttonNext = this.clip.before(this.options.buttonNextHTML).prev();

        this.buttonNext.addClass(this.className('jcarousel-next'));

        this.clip.addClass(this.className('jcarousel-clip'));
        this.list.addClass(this.className('jcarousel-list'));
        this.container.addClass(this.className('jcarousel-container'));

        var di = this.options.visible != null ? Math.ceil(this.clipping() / this.options.visible) : null;
        var li = this.list.children('li');

        var self = this;

        if (li.size() > 0) {
            var wh = 0, i = this.options.offset;
            li.each(function() {
                self.format(this, i++);
                wh += self.dimension(this, di);
            });

            this.list.css(this.wh, wh + 'px');

            // Only set if not explicitly passed as option
            if (!o || o.size === undefined)
                this.options.size = li.size();
        }

        // For whatever reason, .show() does not work in Safari...
        this.container.css('display', 'block');
        this.buttonNext.css('display', 'block');
        this.buttonPrev.css('display', 'block');

        this.funcNext   = function() { self.next(); };
        this.funcPrev   = function() { self.prev(); };
        this.funcResize = function() { /*self.reload();*/ };

        if (this.options.initCallback != null)
            this.options.initCallback(this, 'init');

//        if ($.browser.safari) {
//            this.buttons(false, false);
//            $(window).bind('load', function() { self.setup(); });
//        } else
            this.setup();
    };

    // Create shortcut for internal use
    var $jc = $.jcarousel;

    $jc.fn = $jc.prototype = {
        jcarousel: '0.2.3'
    };

    $jc.fn.extend = $jc.extend = $.extend;

    $jc.fn.extend({
        /**
         * Setups the carousel.
         *
         * @name setup
         * @type undefined
         * @cat Plugins/jCarousel
         */
        setup: function() {
            this.first     = null;
            this.last      = null;
            this.prevFirst = null;
            this.prevLast  = null;
            this.animating = false;
            this.timer     = null;
            this.tail      = null;
            this.inTail    = false;

            if (this.locked)
                return;

            this.list.css(this.lt, this.pos(this.options.offset) + 'px');
            var p = this.pos(this.options.start);
            this.prevFirst = this.prevLast = null;
            this.animate(p, false);

            $(window).unbind('resize', this.funcResize).bind('resize', this.funcResize);
        },

        /**
         * Clears the list and resets the carousel.
         *
         * @name reset
         * @type undefined
         * @cat Plugins/jCarousel
         */
        reset: function() {
            this.list.empty();

            this.list.css(this.lt, '0px');
            this.list.css(this.wh, '10px');

            if (this.options.initCallback != null)
                this.options.initCallback(this, 'reset');

            this.setup();
        },

        /**
         * Reloads the carousel and adjusts positions.
         *
         * @name reload
         * @type undefined
         * @cat Plugins/jCarousel
         */
        reload: function() {
            if (this.tail != null && this.inTail)
                this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) + this.tail);

            this.tail   = null;
            this.inTail = false;

            if (this.options.reloadCallback != null)
                this.options.reloadCallback(this);

            if (this.options.visible != null) {
                var self = this;
                var di = Math.ceil(this.clipping() / this.options.visible), wh = 0, lt = 0;
                $('li', this.list).each(function(i) {
                    wh += self.dimension(this, di);
                    if (i + 1 < self.first)
                        lt = wh;
                });

                this.list.css(this.wh, wh + 'px');
                this.list.css(this.lt, -lt + 'px');
            }

            this.scroll(this.first, false);
        },

        /**
         * Locks the carousel.
         *
         * @name lock
         * @type undefined
         * @cat Plugins/jCarousel
         */
        lock: function() {
            this.locked = true;
            this.buttons();
        },

        /**
         * Unlocks the carousel.
         *
         * @name unlock
         * @type undefined
         * @cat Plugins/jCarousel
         */
        unlock: function() {
            this.locked = false;
            this.buttons();
        },

        /**
         * Sets the size of the carousel.
         *
         * @name size
         * @type undefined
         * @param Number s The size of the carousel.
         * @cat Plugins/jCarousel
         */
        size: function(s) {
            if (s != undefined) {
                this.options.size = s;
                if (!this.locked)
                    this.buttons();
            }

            return this.options.size;
        },

        /**
         * Checks whether a list element exists for the given index (or index range).
         *
         * @name get
         * @type bool
         * @param Number i The index of the (first) element.
         * @param Number i2 The index of the last element.
         * @cat Plugins/jCarousel
         */
        has: function(i, i2) {
            if (i2 == undefined || !i2)
                i2 = i;

            if (this.options.size !== null && i2 > this.options.size)
            	i2 = this.options.size;

            for (var j = i; j <= i2; j++) {
                var e = this.get(j);
                if (!e.length || e.hasClass('jcarousel-item-placeholder'))
                    return false;
            }

            return true;
        },

        /**
         * Returns a jQuery object with list element for the given index.
         *
         * @name get
         * @type jQuery
         * @param Number i The index of the element.
         * @cat Plugins/jCarousel
         */
        get: function(i) {
            return $('.jcarousel-item-' + i, this.list);
        },

        /**
         * Adds an element for the given index to the list.
         * If the element already exists, it updates the inner html.
         * Returns the created element as jQuery object.
         *
         * @name add
         * @type jQuery
         * @param Number i The index of the element.
         * @param String s The innerHTML of the element.
         * @cat Plugins/jCarousel
         */
        add: function(i, s) {
            var e = this.get(i), old = 0, add = 0;

            if (e.length == 0) {
                var c, e = this.create(i), j = $jc.intval(i);
                while (c = this.get(--j)) {
                    if (j <= 0 || c.length) {
                        j <= 0 ? this.list.prepend(e) : c.after(e);
                        break;
                    }
                }
            } else
                old = this.dimension(e);

            e.removeClass(this.className('jcarousel-item-placeholder'));
            typeof s == 'string' ? e.html(s) : e.empty().append(s);

            var di = this.options.visible != null ? Math.ceil(this.clipping() / this.options.visible) : null;
            var wh = this.dimension(e, di) - old;

            if (i > 0 && i < this.first)
                this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) - wh + 'px');

            this.list.css(this.wh, $jc.intval(this.list.css(this.wh)) + wh + 'px');

            return e;
        },

        /**
         * Removes an element for the given index from the list.
         *
         * @name remove
         * @type undefined
         * @param Number i The index of the element.
         * @cat Plugins/jCarousel
         */
        remove: function(i) {
            var e = this.get(i);

            // Check if item exists and is not currently visible
            if (!e.length || (i >= this.first && i <= this.last))
                return;

            var d = this.dimension(e);

            if (i < this.first)
                this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) + d + 'px');

            e.remove();

            this.list.css(this.wh, $jc.intval(this.list.css(this.wh)) - d + 'px');
        },

        /**
         * Moves the carousel forwards.
         *
         * @name next
         * @type undefined
         * @cat Plugins/jCarousel
         */
        next: function() {
            this.stopAuto();

            if (this.tail != null && !this.inTail)
                this.scrollTail(false);
            else
                this.scroll(((this.options.wrap == 'both' || this.options.wrap == 'last') && this.options.size != null && this.last == this.options.size) ? 1 : this.first + this.options.scroll);
        },

        /**
         * Moves the carousel backwards.
         *
         * @name prev
         * @type undefined
         * @cat Plugins/jCarousel
         */
        prev: function() {
            this.stopAuto();

            if (this.tail != null && this.inTail)
                this.scrollTail(true);
            else
                this.scroll(((this.options.wrap == 'both' || this.options.wrap == 'first') && this.options.size != null && this.first == 1) ? this.options.size : this.first - this.options.scroll);
        },

        /**
         * Scrolls the tail of the carousel.
         *
         * @name scrollTail
         * @type undefined
         * @param Bool b Whether scroll the tail back or forward.
         * @cat Plugins/jCarousel
         */
        scrollTail: function(b) {
            if (this.locked || this.animating || !this.tail)
                return;

            var pos  = $jc.intval(this.list.css(this.lt));

            !b ? pos -= this.tail : pos += this.tail;
            this.inTail = !b;

            // Save for callbacks
            this.prevFirst = this.first;
            this.prevLast  = this.last;

            this.animate(pos);
        },

        /**
         * Scrolls the carousel to a certain position.
         *
         * @name scroll
         * @type undefined
         * @param Number i The index of the element to scoll to.
         * @param Bool a Flag indicating whether to perform animation.
         * @cat Plugins/jCarousel
         */
        scroll: function(i, a) {
            if (this.locked || this.animating)
                return;

            this.animate(this.pos(i), a);
        },

        /**
         * Prepares the carousel and return the position for a certian index.
         *
         * @name pos
         * @type Number
         * @param Number i The index of the element to scoll to.
         * @cat Plugins/jCarousel
         */
        pos: function(i) {
            if (this.locked || this.animating)
                return;

            i = $jc.intval(i);
            if (this.options.wrap != 'circular')
                i = i < 1 ? 1 : (this.options.size && i > this.options.size ? this.options.size : i);

            var back = this.first > i;
            var pos  = $jc.intval(this.list.css(this.lt));

            // Create placeholders, new list width/height
            // and new list position
            var f = this.options.wrap != 'circular' && this.first <= 1 ? 1 : this.first;
            var c = back ? this.get(f) : this.get(this.last);
            var j = back ? f : f - 1;
            var e = null, l = 0, p = false, d = 0;

            while (back ? --j >= i : ++j < i) {
                e = this.get(j);
                p = !e.length;
                if (e.length == 0) {
                    e = this.create(j).addClass(this.className('jcarousel-item-placeholder'));
                    c[back ? 'before' : 'after' ](e);
                }
                c = e;
                d = this.dimension(e);

                if (p)
                    l += d;
                if (this.first != null && (this.options.wrap == 'circular' || (j >= 1 && (this.options.size == null || j <= this.options.size))))
                    pos = back ? pos + d : pos - d;
            }
            // Calculate visible items
            var clipping = this.clipping();
            var cache = [];
            var visible = 0, j = i, v = 0;
            var c = this.get(i - 1);
            while (++visible) {
                e = this.get(j);
                p = !e.length;
                if (e.length == 0) {
                    e = this.create(j).addClass(this.className('jcarousel-item-placeholder'));
                    // This should only happen on a next scroll
                    c.length == 0 ? this.list.prepend(e) : c[back ? 'before' : 'after' ](e);
                }
                c = e;
                var d = this.dimension(e);
                if (d == 0) {
                    alert('jCarousel: No width/height set for items. This will cause an infinite loop. Aborting...');
                    return 0;
                }
                if (this.options.wrap != 'circular' && this.options.size !== null && j > this.options.size)
                    cache.push(e);
                else if (p)
                    l += d;
                v += d;
                if (v >= clipping)
                    break;
                j++;
            }
             // Remove out-of-range placeholders
            for (var x = 0; x < cache.length; x++)
                cache[x].remove();
            // Resize list
            if (l > 0) {
                this.list.css(this.wh, this.dimension(this.list) + l + 'px');
                if (back) {
                    pos -= l;
                    this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) - l + 'px');
                }
            }
            // Calculate first and last item
            var last = i + visible - 1;
            if (this.options.wrap != 'circular' && this.options.size && last > this.options.size)
                last = this.options.size;
            if (j > last) {
                visible = 0, j = last, v = 0;
                while (++visible) {
                    var e = this.get(j--);
                    if (!e.length)
                        break;
                    v += this.dimension(e);
                    if (v >= clipping)
                        break;
                }
            }
            var first = last - visible + 1;
            if (this.options.wrap != 'circular' && first < 1)
                first = 1;
            if (this.inTail && back) {
                pos += this.tail;
                this.inTail = false;
            }
            this.tail = null;
            if (this.options.wrap != 'circular' && last == this.options.size && (last - visible + 1) >= 1) {
                var m = $jc.margin(this.get(last), !this.options.vertical ? 'marginRight' : 'marginBottom');
                if ((v - m) > clipping)
                    this.tail = v - clipping - m;
            }
            // Adjust position
            while (i-- > first)
                pos += this.dimension(this.get(i));
            // Save visible item range
            this.prevFirst = this.first;
            this.prevLast  = this.last;
            this.first     = first;
            this.last      = last;

            return pos;
        },
        /**
         * Animates the carousel to a certain position.
         * @name animate
         * @type undefined
         * @param mixed p Position to scroll to.
         * @param Bool a Flag indicating whether to perform animation.
         * @cat Plugins/jCarousel
         */
        animate: function(p, a) {
            if (this.locked || this.animating)
                return;
            this.animating = true;
            var self = this;
            var scrolled = function() {
                self.animating = false;
                if (p == 0)
                    self.list.css(self.lt,  0);
                if (self.options.wrap == 'both' || self.options.wrap == 'last' || self.options.size == null || self.last < self.options.size)
                    self.startAuto();
                self.buttons();
                self.notify('onAfterAnimation');
            };
            this.notify('onBeforeAnimation');
            // Animate
            if (!this.options.animation || a == false) {
                this.list.css(this.lt, p + 'px');
                scrolled();
            } else {
                var o = !this.options.vertical ? {'left': p} : {'top': p};
                this.list.animate(o, this.options.animation, this.options.easing, scrolled);
            }
        },
        /**
         * Starts autoscrolling.
         * @name auto
         * @type undefined
         * @param Number s Seconds to periodically autoscroll the content.
         * @cat Plugins/jCarousel
         */
        startAuto: function(s) {
            if (s != undefined)
                this.options.auto = s;
            if (this.options.auto == 0)
                return this.stopAuto();
            if (this.timer != null)
                return;
            var self = this;
            this.timer = setTimeout(function() { self.next(); }, this.options.auto * 1000);
        },
        /**
         * Stops autoscrolling.
         * @name stopAuto
         * @type undefined
         * @cat Plugins/jCarousel
         */
        stopAuto: function() {
            if (this.timer == null)
                return;
            clearTimeout(this.timer);
            this.timer = null;
        },
        /**
         * Sets the states of the prev/next buttons.
         * @name buttons
         * @type undefined
         * @cat Plugins/jCarousel
         */
        buttons: function(n, p) {
            if (n == undefined || n == null) {
                var n = !this.locked && this.options.size !== 0 && ((this.options.wrap && this.options.wrap != 'first') || this.options.size == null || this.last < this.options.size);
                if (!this.locked && (!this.options.wrap || this.options.wrap == 'first') && this.options.size != null && this.last >= this.options.size)
                    n = this.tail != null && !this.inTail;
            }
            if (p == undefined || p == null) {
                var p = !this.locked && this.options.size !== 0 && ((this.options.wrap && this.options.wrap != 'last') || this.first > 1);
                if (!this.locked && (!this.options.wrap || this.options.wrap == 'last') && this.options.size != null && this.first == 1)
                    p = this.tail != null && this.inTail;
            }
            var self = this;
            this.buttonNext[n ? 'bind' : 'unbind'](this.options.buttonNextEvent, this.funcNext)[n ? 'removeClass' : 'addClass'](this.className('jcarousel-next-disabled')).attr('disabled', n ? false : true);
            this.buttonPrev[p ? 'bind' : 'unbind'](this.options.buttonPrevEvent, this.funcPrev)[p ? 'removeClass' : 'addClass'](this.className('jcarousel-prev-disabled')).attr('disabled', p ? false : true);
            if (this.buttonNext.length > 0 && (this.buttonNext[0].jcarouselstate == undefined || this.buttonNext[0].jcarouselstate != n) && this.options.buttonNextCallback != null) {
                this.buttonNext.each(function() { self.options.buttonNextCallback(self, this, n); });
                this.buttonNext[0].jcarouselstate = n;
            }
            if (this.buttonPrev.length > 0 && (this.buttonPrev[0].jcarouselstate == undefined || this.buttonPrev[0].jcarouselstate != p) && this.options.buttonPrevCallback != null) {
                this.buttonPrev.each(function() { self.options.buttonPrevCallback(self, this, p); });
                this.buttonPrev[0].jcarouselstate = p;
            }
        },
        notify: function(evt) {
            var state = this.prevFirst == null ? 'init' : (this.prevFirst < this.first ? 'next' : 'prev');
            // Load items
            this.callback('itemLoadCallback', evt, state);
            if (this.prevFirst !== this.first) {
                this.callback('itemFirstInCallback', evt, state, this.first);
                this.callback('itemFirstOutCallback', evt, state, this.prevFirst);
            }
            if (this.prevLast !== this.last) {
                this.callback('itemLastInCallback', evt, state, this.last);
                this.callback('itemLastOutCallback', evt, state, this.prevLast);
            }
            this.callback('itemVisibleInCallback', evt, state, this.first, this.last, this.prevFirst, this.prevLast);
            this.callback('itemVisibleOutCallback', evt, state, this.prevFirst, this.prevLast, this.first, this.last);
        },
        callback: function(cb, evt, state, i1, i2, i3, i4) {
            if (this.options[cb] == undefined || (typeof this.options[cb] != 'object' && evt != 'onAfterAnimation'))
                return;
            var callback = typeof this.options[cb] == 'object' ? this.options[cb][evt] : this.options[cb];
            if (!$.isFunction(callback))
                return;
            var self = this;
            if (i1 === undefined)
                callback(self, state, evt);
            else if (i2 === undefined)
                this.get(i1).each(function() { callback(self, this, i1, state, evt); });
            else {
                for (var i = i1; i <= i2; i++)
                    if (i !== null && !(i >= i3 && i <= i4))
                        this.get(i).each(function() { callback(self, this, i, state, evt); });
            }
        },
        create: function(i) {
            return this.format('<li></li>', i);
        },
        format: function(e, i) {
            var $e = $(e).addClass(this.className('jcarousel-item')).addClass(this.className('jcarousel-item-' + i));
            $e.attr('jcarouselindex', i);
            return $e;
        },
        className: function(c) {
            return c + ' ' + c + (!this.options.vertical ? '-horizontal' : '-vertical');
        },
        dimension: function(e, d) {
            var el = e.jquery != undefined ? e[0] : e;
            var old = !this.options.vertical ?
                el.offsetWidth + $jc.margin(el, 'marginLeft') + $jc.margin(el, 'marginRight') :
                el.offsetHeight + $jc.margin(el, 'marginTop') + $jc.margin(el, 'marginBottom');
            if (d == undefined || old == d)
                return old;
            var w = !this.options.vertical ?
                d - $jc.margin(el, 'marginLeft') - $jc.margin(el, 'marginRight') :
                d - $jc.margin(el, 'marginTop') - $jc.margin(el, 'marginBottom');
            $(el).css(this.wh, w + 'px');
            return this.dimension(el);
        },
        clipping: function() {
            return !this.options.vertical ?
                this.clip[0].offsetWidth - $jc.intval(this.clip.css('borderLeftWidth')) - $jc.intval(this.clip.css('borderRightWidth')) :
                this.clip[0].offsetHeight - $jc.intval(this.clip.css('borderTopWidth')) - $jc.intval(this.clip.css('borderBottomWidth'));
        },
        index: function(i, s) {
            if (s == undefined)
                s = this.options.size;
            return Math.round((((i-1) / s) - Math.floor((i-1) / s)) * s) + 1;
        }
    });
    $jc.extend({
        /**
         * Gets/Sets the global default configuration properties.
         *
         * @name defaults
         * @descr Gets/Sets the global default configuration properties.
         * @type Hash
         * @param Hash d A set of key/value pairs to set as configuration properties.
         * @cat Plugins/jCarousel
         */
        defaults: function(d) {
            return $.extend(defaults, d || {});
        },
        margin: function(e, p) {
            if (!e)
                return 0;
            var el = e.jquery != undefined ? e[0] : e;
            if (p == 'marginRight' && $.browser.safari) {
                var old = {'display': 'block', 'float': 'none', 'width': 'auto'}, oWidth, oWidth2;
                $.swap(el, old, function() { oWidth = el.offsetWidth; });
                old['marginRight'] = 0;
                $.swap(el, old, function() { oWidth2 = el.offsetWidth; });
                return oWidth2 - oWidth;
            }
            return $jc.intval($.css(el, p));
        },
        intval: function(v) {
            v = parseInt(v);
            return isNaN(v) ? 0 : v;
        }
    });
})(jQuery);
/*
 * Thickbox 3.1 - One Box To Rule Them All.
 * By Cody Lindley (http://www.codylindley.com)
 * Copyright (c) 2007 cody lindley
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
var tb_pathToImage = HTTP+ "_layouts/images/ajax-loader.gif";
/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/
// fixes the fact that ie7 now reports itself as MSIE 6.0 compatible
/*$j.browser.msie6 = 
        $j.browser.msie 
        && /MSIE 6\.0/i.test(window.navigator.userAgent) 
        && !/MSIE 7\.0/i.test(window.navigator.userAgent);*/
if ( document.all && !window.opera && !window.XMLHttpRequest && $j.browser.msie )
{var isIE6 = true;}
else
{ var isIE6 = false;} ;
$j.browser.msie6 = isIE6;
//on page load call tb_init
$j(document).ready(function(){   
	tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
	imgLoader = new Image();// preload image
	imgLoader.src = tb_pathToImage;
});
//add thickbox to href & area elements that have a class of .thickbox
function tb_init(domChunk){
	$j(domChunk).click(function(){
	var t = this.title || this.name || null;
	var a = this.href || this.alt;
	var g = this.rel || false;
	tb_show(t,a,g);
	this.blur();
	return false;
	});
}
function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link
	//$j("#TB_window").css('display','none');
	try {
		if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
			$j("body","html").css({height: "100%", width: "100%"});
			$j("html").css("overflow","hidden");
			if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
				$j("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
				$j("#TB_overlay").click(tb_remove);
			}
		}else{//all others
			if(document.getElementById("TB_overlay") === null){
				$j("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
				$j("#TB_overlay").click(tb_remove);
			}
		}
		if(tb_detectMacXFF()){
			$j("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
		}else{
			$j("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
		}
		if(caption===null){caption="";}
		$j("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
		$j('#TB_load').show();//show loader
		var baseURL;
	   if(url.indexOf("?")!==-1){ //ff there is a query string involved
			baseURL = url.substr(0, url.indexOf("?"));
	   }else{ 
	   		baseURL = url;
	   }
	   var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
	   var urlType = baseURL.toLowerCase().match(urlString);
		if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images
			TB_PrevCaption = "";
			TB_PrevURL = "";
			TB_PrevHTML = "";
			TB_NextCaption = "";
			TB_NextURL = "";
			TB_NextHTML = "";
			TB_imageCount = "";
			TB_FoundURL = false;
			if(imageGroup){
				TB_TempArray = $j("a[@rel="+imageGroup+"]").get();
				for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) {
					var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
						if (!(TB_TempArray[TB_Counter].href == url)) {						
							if (TB_FoundURL) {
								TB_NextCaption = TB_TempArray[TB_Counter].title;
								TB_NextURL = TB_TempArray[TB_Counter].href;
								TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";
							} else {
								TB_PrevCaption = TB_TempArray[TB_Counter].title;
								TB_PrevURL = TB_TempArray[TB_Counter].href;
								TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";
							}
						} else {
							TB_FoundURL = true;
							TB_imageCount = "Image " + (TB_Counter + 1) +" of "+ (TB_TempArray.length);											
						}
				}
			}
			imgPreloader = new Image();
			imgPreloader.onload = function(){		
			imgPreloader.onload = null;
			// Resizing large images - orginal by Christian Montoya edited by me.
			var pagesize = tb_getPageSize();
			var x = pagesize[0] - 150;
			var y = pagesize[1] - 150;
			var imageWidth = imgPreloader.width;
			var imageHeight = imgPreloader.height;
			if (imageWidth > x) {
				imageHeight = imageHeight * (x / imageWidth); 
				imageWidth = x; 
				if (imageHeight > y) { 
					imageWidth = imageWidth * (y / imageHeight); 
					imageHeight = y; 
				}
			} else if (imageHeight > y) { 
				imageWidth = imageWidth * (y / imageHeight); 
				imageHeight = y; 
				if (imageWidth > x) { 
					imageHeight = imageHeight * (x / imageWidth); 
					imageWidth = x;
				}
			}// End Resizing
			TB_WIDTH = imageWidth + 30;
			TB_HEIGHT = imageHeight + 60;
			$j("#TB_window").append("<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div>"); 		
			$j("#TB_closeWindowButton").click(tb_remove);
			if (!(TB_PrevHTML === "")) {
				function goPrev(){
					if($j(document).unbind("click",goPrev)){$j(document).unbind("click",goPrev);}
					$j("#TB_window").remove();
					$j("body").append("<div id='TB_window'></div>");
					tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
					return false;	
				}
				$j("#TB_prev").click(goPrev);
			}
			if (!(TB_NextHTML === "")) {		
				function goNext(){
					$j("#TB_window").remove();
					$j("body").append("<div id='TB_window'></div>");
					tb_show(TB_NextCaption, TB_NextURL, imageGroup);				
					return false;	
				}
				$j("#TB_next").click(goNext);
				
			}
			document.onkeydown = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tb_remove();
				} else if(keycode == 190){ // display previous image
					if(!(TB_NextHTML == "")){
						document.onkeydown = "";
						goNext();
					}
				} else if(keycode == 188){ // display next image
					if(!(TB_PrevHTML == "")){
						document.onkeydown = "";
						goPrev();
					}
				}	
			};
			tb_position();
			$j("#TB_load").remove();
			$j("#TB_ImageOff").click(tb_remove);
			$j("#TB_window").css({display:"block"}); //for safari using css instead of show
			};
			imgPreloader.src = url;
		}else{//code to show html
			var queryString = url.replace(/^[^\?]+\??/,'');
			var params = tb_parseQuery( queryString );
			TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
			TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
			ajaxContentW = TB_WIDTH - 30;
			ajaxContentH = TB_HEIGHT - 40;
			if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window		
					urlNoQuery = url.split('TB_');
					$j("#TB_iframeContent").remove();
					if(params['modal'] != "true"){//iframe no modal
						$j("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>");
					}else{//iframe modal
					$j("#TB_overlay").unbind();
						$j("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>");
					}
			}else{// not an iframe, ajax
					if($j("#TB_window").css("display") != "block"){
						if(params['modal'] != "true"){//ajax no modal
						$j("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>close</a></div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
						}else{//ajax modal
						$j("#TB_overlay").unbind();
						//$j("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");
						$j("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;'></div>");
						}
					}else{//this means the window is already up, we are just loading new content via ajax
						$j("#TB_ajaxContent")[0].style.width = ajaxContentW +"px";
						//$j("#TB_ajaxContent")[0].style.height = ajaxContentH +"px";
						$j("#TB_ajaxContent")[0].scrollTop = 0;
						$j("#TB_ajaxWindowTitle").html(caption);
					}
			}
			$j("#TB_closeWindowButton").click(tb_remove);
				if(url.indexOf('TB_inline') != -1){	
					$j("#TB_ajaxContent").append($j('#' + params['inlineId']).children());
					$j("#TB_window").unload(function () {
						$j('#' + params['inlineId']).append( $j("#TB_ajaxContent").children() ); // move elements back when you're finished
					});
					tb_position();
					$j("#TB_load").remove();
					$j("#TB_window").css({display:"block"}); 
				}else if(url.indexOf('TB_iframe') != -1){
					tb_position();
					if($j.browser.safari){//safari needs help because it will not fire iframe onload
						$j("#TB_load").remove();
						$j("#TB_window").css({display:"block"});
					}
				}else{
					$j("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
						tb_position();
						$j("#TB_load").remove();
						tb_init("#TB_ajaxContent a.thickbox");
						$j("#TB_window").css({display:"block"});
					});
				}
		}
		if(params['onTop']){
			$j("#TB_window").css({'position':"absolute",'top':'30px','margin-top':"0px"});
		}
		if($j('#TB_closeX').length<1){
			$j("#TB_window").prepend('<span id="TB_closeX"></span>');
			$j("#TB_closeX").click(tb_remove);
		}
		if(!params['modal']){
			document.onkeyup = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tb_remove();
				}	
			};
		}
	} catch(e) {//nothing here
	}
}//helper functions below
function tb_showIframe(){
	$j("#TB_load").remove();
	$j("#TB_window").css({display:"block"});
}
function tb_remove() {
 	$j("#TB_imageOff").unbind("click");
	$j("#TB_closeWindowButton").unbind("click");
	$j("#TB_window").fadeOut("fast",function(){$j('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});
	$j("#TB_load").remove();
	if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
		$j("body","html").css({height: "auto", width: "auto"});
		$j("html").css("overflow","");
	}
	document.onkeydown = "";
	document.onkeyup = "";
	setTimeout("$j('#cluetip').css('display','none');",250);
	return false;
}
function tb_position() {
$j("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
	if ( !(jQuery.browser.msie6)) { // take away IE6
		if($j("#TB_window").css('position') != 'absolute')
		$j("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
	}
}
function tb_parseQuery ( query ) {
   var Params = {};
   if ( ! query ) {return Params;}// return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}
function tb_getPageSize(){
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
	arrayPageSize = [w,h];
	return arrayPageSize;
}
function tb_detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}// end of thickbox
/**
*	@name							Elastic
*	@descripton						Elastic is Jquery plugin that grow and shrink your textareas automaticliy
*	@version						1.6.3
*	@requires						Jquery 1.2.6+
*	@author							Jan Jarfalk
*	@author-email					jan.jarfalk@unwrongest.com
*	@author-website					http://www.unwrongest.com
*	@licens							MIT License - http://www.opensource.org/licenses/mit-license.php
*/
(function(jQuery){ 
	jQuery.fn.extend({  
		elastic: function() {
			//	We will create a div clone of the textarea
			//	by copying these attributes from the textarea to the div.
			var mimics = [
				'paddingTop',
				'paddingRight',
				'paddingBottom',
				'paddingLeft',
				'fontSize',
				'lineHeight',
				'fontFamily',
				'width',
				'fontWeight'];
			return this.each( function() {
				// Elastic only works on textareas
				if ( this.type != 'textarea' ) {
					return false;
				}
				var $textarea	=	jQuery(this),
					$twin		=	jQuery('<div class="twin" />').css({'position': 'absolute','display':'none','word-wrap':'break-word'}),
					lineHeight	=	parseInt($textarea.css('line-height'),10) || parseInt($textarea.css('font-size'),'10'),
					minheight	=	parseInt($textarea.css('height'),10) || lineHeight*1,
					maxheight	=	parseInt($textarea.css('max-height'),10) || Number.MAX_VALUE,
					goalheight	=	0,
					i 			=	0;
				//alert(minheight);
				// Opera returns max-height of -1 if not set
				if (maxheight < 0) { maxheight = Number.MAX_VALUE; }
				// Append the twin to the DOM
				// We are going to meassure the height of this, not the textarea.
				$twin.appendTo($textarea.parent());
				// Copy the essential styles (mimics) from the textarea to the twin
				var i = mimics.length;
				while(i--){
					$twin.css(mimics[i].toString(),$textarea.css(mimics[i].toString()));
				}
				// Sets a given height and overflow state on the textarea
				function setHeightAndOverflow(height, overflow){
					curratedHeight = Math.floor(parseInt(height,10));
					if($textarea.height() != curratedHeight){
						$textarea.css({'height': curratedHeight + 'px','overflow':overflow});
					}
				}
				// This function will update the height of the textarea if necessary 
				function update() {
					// Get curated content from the textarea.
					var textareaContent = $textarea.val().replace(/&/g,'&amp;').replace(/  /g, '&nbsp;').replace(/<|>/g, '&gt;').replace(/\n/g, '<br />');
					var twinContent = $twin.html();
					if(textareaContent+'&nbsp;' != twinContent){
						// Add an extra white space so new rows are added when you are at the end of a row.
						$twin.html(textareaContent+'&nbsp;');
						// Change textarea height if twin plus the height of one line differs more than 3 pixel from textarea height
						//if(Math.abs($twin.height()+lineHeight - $textarea.height()) > 3){
						if(Math.abs($twin.height() - $textarea.height()) > 3){
							//var goalheight = $twin.height()+lineHeight;
							var goalheight = $twin.height();
							if(goalheight >= maxheight) {
								setHeightAndOverflow(maxheight,'auto');
							} else if(goalheight <= minheight) {
								setHeightAndOverflow(minheight,'hidden');
							} else {
								setHeightAndOverflow(goalheight,'hidden');
							}
						}
					}
				}
				// Hide scrollbars
				$textarea.css({'overflow':'hidden'});
				// Update textarea size on keyup
				$textarea.keyup(function(){ update(); });
				// And this line is to catch the browser paste event
				$textarea.live('input paste',function(e){ setTimeout( update, 250); });				
				// Run update once when elastic is initialized
				update();
			});
        } 
    }); 
})(jQuery);
/* jQuery Form Plugin
 * version: 2.12 (06/07/2008)
 * @requires jQuery v1.2.2 or later
 * Examples and documentation at: http://malsup.com/jquery/form/
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id$
 */
(function($) {
/*
    Usage Note:  
    -----------
    Do not use both ajaxSubmit and ajaxForm on the same form.  These
    functions are intended to be exclusive.  Use ajaxSubmit if you want
    to bind your own submit handler to the form.  For example,
    $(document).ready(function() {
        $('#myForm').bind('submit', function() {
            $(this).ajaxSubmit({
                target: '#output'
            });
            return false; // <-- important!
        });
    });
    Use ajaxForm when you want the plugin to manage all the event binding
    for you.  For example,
    $(document).ready(function() {
        $('#myForm').ajaxForm({
            target: '#output'
        });
    });
    When using ajaxForm, the ajaxSubmit function will be invoked for you
    at the appropriate time.  
*/
/**
 * ajaxSubmit() provides a mechanism for immediately submitting 
 * an HTML form using AJAX.
 */
$.fn.ajaxSubmit = function(options) {
    // fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
    if (!this.length) {
        log('ajaxSubmit: skipping submit process - no element selected');
        return this;
    }
    if (typeof options == 'function')
        options = { success: options };
    options = $.extend({
        url:  this.attr('action') || window.location.toString(),
        type: this.attr('method') || 'GET'
    }, options || {});
    // hook for manipulating the form data before it is extracted;
    // convenient for use with rich editors like tinyMCE or FCKEditor
    var veto = {};
    this.trigger('form-pre-serialize', [this, options, veto]);
    if (veto.veto) {
        log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
        return this;
   }
    var a = this.formToArray(options.semantic);
    if (options.data) {
        options.extraData = options.data;
        for (var n in options.data)
            a.push( { name: n, value: options.data[n] } );
    }
    // give pre-submit callback an opportunity to abort the submit
    if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
        log('ajaxSubmit: submit aborted via beforeSubmit callback');
        return this;
    }    
    // fire vetoable 'validate' event
    this.trigger('form-submit-validate', [a, this, options, veto]);
    if (veto.veto) {
        log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
        return this;
    }    
    var q = $.param(a);
    if (options.type.toUpperCase() == 'GET') {
        options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
        options.data = null;  // data is null for 'get'
    }
    else
        options.data = q; // data is the query string for 'post'
    var $form = this, callbacks = [];
    if (options.resetForm) callbacks.push(function() { $form.resetForm(); });
    if (options.clearForm) callbacks.push(function() { $form.clearForm(); });
    // perform a load on the target only if dataType is not provided
    if (!options.dataType && options.target) {
        var oldSuccess = options.success || function(){};
        callbacks.push(function(data) {
            $(options.target).html(data).each(oldSuccess, arguments);
        });
    }
    else if (options.success)
        callbacks.push(options.success);
    options.success = function(data, status) {
        for (var i=0, max=callbacks.length; i < max; i++)
            callbacks[i](data, status, $form);
    };
    // are there files to upload?
    var files = $('input:file', this).fieldValue();
    var found = false;
    for (var j=0; j < files.length; j++)
        if (files[j])
            found = true;
    // options.iframe allows user to force iframe mode
   if (options.iframe || found) { 
       // hack to fix Safari hang (thanks to Tim Molendijk for this)
       // see:  http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
       if ($.browser.safari && options.closeKeepAlive)
           $.get(options.closeKeepAlive, fileUpload);
       else
           fileUpload();
       }
   else
       $.ajax(options);
    // fire 'notify' event
    this.trigger('form-submit-notify', [this, options]);
    return this;
    // private function for handling file uploads (hat tip to YAHOO!)
    function fileUpload() {
        var form = $form[0];
        if ($(':input[name=submit]', form).length) {
            alert('Error: Form elements must not be named "submit".');
            return;
        }
        var opts = $.extend({}, $.ajaxSettings, options);
        var id = 'jqFormIO' + (new Date().getTime());
        var $io = $('<iframe id="' + id + '" name="' + id + '" />');
        var io = $io[0];
        if ($.browser.msie || $.browser.opera) 
            io.src = 'javascript:false;document.write("");';
        $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
        var xhr = { // mock object
            responseText: null,
            responseXML: null,
            status: 0,
            statusText: 'n/a',
            getAllResponseHeaders: function() {},
            getResponseHeader: function() {},
            setRequestHeader: function() {}
        };
        var g = opts.global;
        // trigger ajax global events so that activity/block indicators work like normal
        if (g && ! $.active++) $.event.trigger("ajaxStart");
        if (g) $.event.trigger("ajaxSend", [xhr, opts]);
        var cbInvoked = 0;
        var timedOut = 0;
        // add submitting element to data if we know it
        var sub = form.clk;
        if (sub) {
            var n = sub.name;
            if (n && !sub.disabled) {
                options.extraData = options.extraData || {};
                options.extraData[n] = sub.value;
                if (sub.type == "image") {
                    options.extraData[name+'.x'] = form.clk_x;
                    options.extraData[name+'.y'] = form.clk_y;
                }
            }
        }
        // take a breath so that pending repaints get some cpu time before the upload starts
        setTimeout(function() {
            // make sure form attrs are set
            var t = $form.attr('target'), a = $form.attr('action');
            $form.attr({
                target:   id,
                encoding: 'multipart/form-data',
                enctype:  'multipart/form-data',
                method:   'POST',
                action:   opts.url
            });
            // support timout
            if (opts.timeout)
                setTimeout(function() { timedOut = true; cb(); }, opts.timeout);
            // add "extra" data to form if provided in options
            var extraInputs = [];
            try {
                if (options.extraData)
                    for (var n in options.extraData)
                        extraInputs.push(
                            $('<input type="hidden" name="'+n+'" value="'+options.extraData[n]+'" />')
                                .appendTo(form)[0]);
            
                // add iframe to doc and submit the form
                $io.appendTo('body');
                io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
                form.submit();
            }
            finally {
                // reset attrs and remove "extra" input elements
                $form.attr('action', a);
                t ? $form.attr('target', t) : $form.removeAttr('target');
                $(extraInputs).remove();
            }
        }, 10);
        function cb() {
            if (cbInvoked++) return;
            io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);
            var operaHack = 0;
            var ok = true;
            try {
                if (timedOut) throw 'timeout';
                // extract the server response from the iframe
                var data, doc;
                doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
                if (doc.body == null && !operaHack && $.browser.opera) {
                    // In Opera 9.2.x the iframe DOM is not always traversable when
                    // the onload callback fires so we give Opera 100ms to right itself
                    operaHack = 1;
                    cbInvoked--;
                    setTimeout(cb, 100);
                    return;
                }
                xhr.responseText = doc.body ? doc.body.innerHTML : null;
                xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
                xhr.getResponseHeader = function(header){
                    var headers = {'content-type': opts.dataType};
                    return headers[header];
                };
                if (opts.dataType == 'json' || opts.dataType == 'script') {
                    var ta = doc.getElementsByTagName('textarea')[0];
                    xhr.responseText = ta ? ta.value : xhr.responseText;
                }
                else if (opts.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
                    xhr.responseXML = toXml(xhr.responseText);
                }
                data = $.httpData(xhr, opts.dataType);
            }
            catch(e){
                ok = false;
                $.handleError(opts, xhr, 'error', e);
            }
            // ordering of these callbacks/triggers is odd, but that's how $.ajax does it
            if (ok) {
                opts.success(data, 'success');
                if (g) $.event.trigger("ajaxSuccess", [xhr, opts]);
            }
            if (g) $.event.trigger("ajaxComplete", [xhr, opts]);
            if (g && ! --$.active) $.event.trigger("ajaxStop");
            if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error');
            // clean up
            setTimeout(function() {
                $io.remove();
                xhr.responseXML = null;
            }, 100);
        };
        function toXml(s, doc) {
            if (window.ActiveXObject) {
                doc = new ActiveXObject('Microsoft.XMLDOM');
                doc.async = 'false';
                doc.loadXML(s);
            }
            else
                doc = (new DOMParser()).parseFromString(s, 'text/xml');
            return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null;
        };
    };
};
/**
 * ajaxForm() provides a mechanism for fully automating form submission.
 *
 * The advantages of using this method instead of ajaxSubmit() are:
 *
 * 1: This method will include coordinates for <input type="image" /> elements (if the element
 *    is used to submit the form).
 * 2. This method will include the submit element's name/value data (for the element that was
 *    used to submit the form).
 * 3. This method binds the submit() method to the form for you.
 *
 * The options argument for ajaxForm works exactly as it does for ajaxSubmit.  ajaxForm merely
 * passes the options argument along after properly binding events for submit elements and
 * the form itself.
 */ 
$.fn.ajaxForm = function(options) {
    return this.ajaxFormUnbind().bind('submit.form-plugin',function() {
        $(this).ajaxSubmit(options);
        return false;
    }).each(function() {
        // store options in hash
        $(":submit,input:image", this).bind('click.form-plugin',function(e) {
            var $form = this.form;
            $form.clk = this;
            if (this.type == 'image') {
                if (e.offsetX != undefined) {
                    $form.clk_x = e.offsetX;
                    $form.clk_y = e.offsetY;
                } else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
                    var offset = $(this).offset();
                    $form.clk_x = e.pageX - offset.left;
                    $form.clk_y = e.pageY - offset.top;
                } else {
                    $form.clk_x = e.pageX - this.offsetLeft;
                    $form.clk_y = e.pageY - this.offsetTop;
                }
            }
            // clear form vars
            setTimeout(function() { $form.clk = $form.clk_x = $form.clk_y = null; }, 10);
        });
    });
};
// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
$.fn.ajaxFormUnbind = function() {
    this.unbind('submit.form-plugin');
    return this.each(function() {
        $(":submit,input:image", this).unbind('click.form-plugin');
    });

};
/**
 * formToArray() gathers form element data into an array of objects that can
 * be passed to any of the following ajax functions: $.get, $.post, or load.
 * Each object in the array has both a 'name' and 'value' property.  An example of
 * an array for a simple login form might be:
 *
 * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
 *
 * It is this array that is passed to pre-submit callback functions provided to the
 * ajaxSubmit() and ajaxForm() methods.
 */
$.fn.formToArray = function(semantic) {
    var a = [];
    if (this.length == 0) return a;

    var form = this[0];
    var els = semantic ? form.getElementsByTagName('*') : form.elements;
    if (!els) return a;
    for(var i=0, max=els.length; i < max; i++) {
        var el = els[i];
        var n = el.name;
        if (!n) continue;

        if (semantic && form.clk && el.type == "image") {
            // handle image inputs on the fly when semantic == true
            if(!el.disabled && form.clk == el)
                a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
            continue;
        }

        var v = $.fieldValue(el, true);
        if (v && v.constructor == Array) {
            for(var j=0, jmax=v.length; j < jmax; j++)
                a.push({name: n, value: v[j]});
        }
        else if (v !== null && typeof v != 'undefined')
            a.push({name: n, value: v});
    }

    if (!semantic && form.clk) {
        // input type=='image' are not found in elements array! handle them here
        var inputs = form.getElementsByTagName("input");
        for(var i=0, max=inputs.length; i < max; i++) {
            var input = inputs[i];
            var n = input.name;
            if(n && !input.disabled && input.type == "image" && form.clk == input)
                a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
        }
    }
    return a;
};
/**
 * Serializes form data into a 'submittable' string. This method will return a string
 * in the format: name1=value1&amp;name2=value2
 */
$.fn.formSerialize = function(semantic) {
    //hand off to jQuery.param for proper encoding
    return $.param(this.formToArray(semantic));
};
/**
 * Serializes all field elements in the jQuery object into a query string.
 * This method will return a string in the format: name1=value1&amp;name2=value2
 */
$.fn.fieldSerialize = function(successful) {
    var a = [];
    this.each(function() {
        var n = this.name;
        if (!n) return;
        var v = $.fieldValue(this, successful);
        if (v && v.constructor == Array) {
            for (var i=0,max=v.length; i < max; i++)
                a.push({name: n, value: v[i]});
        }
        else if (v !== null && typeof v != 'undefined')
            a.push({name: this.name, value: v});
    });
    //hand off to jQuery.param for proper encoding
    return $.param(a);
};
/**
 * Returns the value(s) of the element in the matched set.  For example, consider the following form:
 *
 *  <form><fieldset>
 *      <input name="A" type="text" />
 *      <input name="A" type="text" />
 *      <input name="B" type="checkbox" value="B1" />
 *      <input name="B" type="checkbox" value="B2"/>
 *      <input name="C" type="radio" value="C1" />
 *      <input name="C" type="radio" value="C2" />
 *  </fieldset></form>
 *
 *  var v = $(':text').fieldValue();
 *  // if no values are entered into the text inputs
 *  v == ['','']
 *  // if values entered into the text inputs are 'foo' and 'bar'
 *  v == ['foo','bar']
 *
 *  var v = $(':checkbox').fieldValue();
 *  // if neither checkbox is checked
 *  v === undefined
 *  // if both checkboxes are checked
 *  v == ['B1', 'B2']
 *
 *  var v = $(':radio').fieldValue();
 *  // if neither radio is checked
 *  v === undefined
 *  // if first radio is checked
 *  v == ['C1']
 *
 * The successful argument controls whether or not the field element must be 'successful'
 * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
 * The default value of the successful argument is true.  If this value is false the value(s)
 * for each element is returned.
 *
 * Note: This method *always* returns an array.  If no valid value can be determined the
 *       array will be empty, otherwise it will contain one or more values.
 */
$.fn.fieldValue = function(successful) {
    for (var val=[], i=0, max=this.length; i < max; i++) {
        var el = this[i];
        var v = $.fieldValue(el, successful);
        if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length))
            continue;
        v.constructor == Array ? $.merge(val, v) : val.push(v);
    }
    return val;
};
/**
 * Returns the value of the field element.
 */
$.fieldValue = function(el, successful) {
    var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
    if (typeof successful == 'undefined') successful = true;

    if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
        (t == 'checkbox' || t == 'radio') && !el.checked ||
        (t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
        tag == 'select' && el.selectedIndex == -1))
            return null;

    if (tag == 'select') {
        var index = el.selectedIndex;
        if (index < 0) return null;
        var a = [], ops = el.options;
        var one = (t == 'select-one');
        var max = (one ? index+1 : ops.length);
        for(var i=(one ? index : 0); i < max; i++) {
            var op = ops[i];
            if (op.selected) {
                // extra pain for IE...
                var v = $.browser.msie && !(op.attributes['value'].specified) ? op.text : op.value;
                if (one) return v;
                a.push(v);
            }
        }
        return a;
    }
    return el.value;
};
/**
 * Clears the form data.  Takes the following actions on the form's input fields:
 *  - input text fields will have their 'value' property set to the empty string
 *  - select elements will have their 'selectedIndex' property set to -1
 *  - checkbox and radio inputs will have their 'checked' property set to false
 *  - inputs of type submit, button, reset, and hidden will *not* be effected
 *  - button elements will *not* be effected
 */
$.fn.clearForm = function() {
    return this.each(function() {
        $('input,select,textarea', this).clearFields();
    });
};
/**
 * Clears the selected form elements.
 */
$.fn.clearFields = $.fn.clearInputs = function() {
    return this.each(function() {
        var t = this.type, tag = this.tagName.toLowerCase();
        if (t == 'text' || t == 'password' || tag == 'textarea')
            this.value = '';
        else if (t == 'checkbox' || t == 'radio')
            this.checked = false;
        else if (tag == 'select')
            this.selectedIndex = -1;
    });
};
/**
 * Resets the form data.  Causes all form elements to be reset to their original value.
 */
$.fn.resetForm = function() {
    return this.each(function() {
        // guard against an input with the name of 'reset'
        // note that IE reports the reset function as an 'object'
        if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
            this.reset();
    });
};
/**
 * Enables or disables any matching elements.
 */
$.fn.enable = function(b) { 
    if (b == undefined) b = true;
    return this.each(function() { 
        this.disabled = !b 
    });
};
/**
 * Checks/unchecks any matching checkboxes or radio buttons and
 * selects/deselects and matching option elements.
 */
$.fn.select = function(select) {
    if (select == undefined) select = true;
    return this.each(function() { 
        var t = this.type;
        if (t == 'checkbox' || t == 'radio')
            this.checked = select;
        else if (this.tagName.toLowerCase() == 'option') {
            var $sel = $(this).parent('select');
            if (select && $sel[0] && $sel[0].type == 'select-one') {
                // deselect all other options
                $sel.find('option').select(false);
            }
            this.selected = select;
        }
    });
};
// helper fn for console logging
// set $.fn.ajaxSubmit.debug to true to enable debug logging
function log() {
    if ($.fn.ajaxSubmit.debug && window.console && window.console.log)
        window.console.log('[jquery.form] ' + Array.prototype.join.call(arguments,''));
};
})(jQuery);
/*
 * jQuery clueTip plugin
 * Version 1.0.4  (June 28, 2009)
 * @requires jQuery v1.2.6+
 *
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
 
/*
 *
 * Full list of options/settings can be found at the bottom of this file and at http://plugins.learningjquery.com/cluetip/
 *
 * Examples can be found at http://plugins.learningjquery.com/cluetip/demo/
 *
*/

;(function($) { 
  $.cluetip = {version: '1.0.4'};
  var $cluetip, $cluetipInner, $cluetipOuter, $cluetipTitle, $cluetipArrows, $cluetipWait, $dropShadow, imgCount;
  $.fn.cluetip = function(js, options) {
    if (typeof js == 'object') {
      options = js;
      js = null;
    }
    if (js == 'destroy') {
      return this.unbind('.cluetip');
    }
    return this.each(function(index) {
      var link = this, $this = $(this);
      
      // support metadata plugin (v1.0 and 2.0)
      var opts = $.extend(true, {}, $.fn.cluetip.defaults, options || {}, $.metadata ? $this.metadata() : $.meta ? $this.data() : {});

      // start out with no contents (for ajax activation)
      var cluetipContents = false;
      var cluezIndex = +opts.cluezIndex;
      $this.data('thisInfo', {title: link.title, zIndex: cluezIndex});
      var isActive = false, closeOnDelay = 0;

      // create the cluetip divs
      if (!$('#cluetip').length) {
        $(['<div id="cluetip">',
          '<div id="cluetip-outer">',
            '<h3 id="cluetip-title"></h3>',
            '<div id="cluetip-inner"></div>',
          '</div>',
          '<div id="cluetip-extra"></div>',
          '<div id="cluetip-arrows" class="cluetip-arrows"></div>',
        '</div>'].join(''))
        [insertionType](insertionElement).hide();
        
        $cluetip = $('#cluetip').css({position: 'absolute'});
        $cluetipOuter = $('#cluetip-outer').css({position: 'relative', zIndex: cluezIndex});
        $cluetipInner = $('#cluetip-inner');
        $cluetipTitle = $('#cluetip-title');        
        $cluetipArrows = $('#cluetip-arrows');
        $cluetipWait = $('<div id="cluetip-waitimage"></div>')
          .css({position: 'absolute'}).insertBefore($cluetip).hide();
      }
      var dropShadowSteps = (opts.dropShadow) ? +opts.dropShadowSteps : 0;
      if (!$dropShadow) {
        $dropShadow = $([]);
        for (var i=0; i < dropShadowSteps; i++) {
          $dropShadow = $dropShadow.add($('<div></div>').css({zIndex: cluezIndex-1, opacity:.1, top: 1+i, left: 1+i}));
        };
        $dropShadow.css({position: 'absolute', backgroundColor: '#000'})
        .prependTo($cluetip);
      }
      var tipAttribute = $this.attr(opts.attribute), ctClass = opts.cluetipClass;
      if (!tipAttribute && !opts.splitTitle && !js) return true;
      // if hideLocal is set to true, on DOM ready hide the local content that will be displayed in the clueTip
      if (opts.local && opts.localPrefix) {tipAttribute = opts.localPrefix + tipAttribute;}
      if (opts.local && opts.hideLocal) { $(tipAttribute + ':first').hide(); }
      var tOffset = parseInt(opts.topOffset, 10), lOffset = parseInt(opts.leftOffset, 10);
      // vertical measurement variables
      var tipHeight, wHeight,
          defHeight = isNaN(parseInt(opts.height, 10)) ? 'auto' : (/\D/g).test(opts.height) ? opts.height : opts.height + 'px';
      var sTop, linkTop, posY, tipY, mouseY, baseline;
      // horizontal measurement variables
      var tipInnerWidth = parseInt(opts.width, 10) || 275,
          tipWidth = tipInnerWidth + (parseInt($cluetip.css('paddingLeft'),10)||0) + (parseInt($cluetip.css('paddingRight'),10)||0) + dropShadowSteps,
          linkWidth = this.offsetWidth,
          linkLeft, posX, tipX, mouseX, winWidth;
            
      // parse the title
      var tipParts;
      var tipTitle = (opts.attribute != 'title') ? $this.attr(opts.titleAttribute) : '';
      if (opts.splitTitle) {
        if(tipTitle == undefined) {tipTitle = '';}
        tipParts = tipTitle.split(opts.splitTitle);
        tipTitle = tipParts.shift();
      }
      if (opts.escapeTitle) {
        tipTitle = tipTitle.replace(/&/g,'&amp;').replace(/>/g,'&gt;').replace(/</g,'&lt;');
      }
      
      var localContent;
      function returnFalse() { return false; }

/***************************************      
* ACTIVATION
****************************************/
    
//activate clueTip
    var activate = function(event) {
      if (!opts.onActivate($this)) {
        return false;
      }
      isActive = true;
      $cluetip.removeClass().css({width: tipInnerWidth});
      if (tipAttribute == $this.attr('href')) {
        $this.css('cursor', opts.cursor);
      }
      if (opts.hoverClass) {
        $this.addClass(opts.hoverClass);
      }
      linkTop = posY = $this.offset().top;
      linkLeft = $this.offset().left;
      mouseX = event.pageX;
      mouseY = event.pageY;
      if (link.tagName.toLowerCase() != 'area') {
        sTop = $(document).scrollTop();
        winWidth = $(window).width();
      }
// position clueTip horizontally
      if (opts.positionBy == 'fixed') {
        posX = linkWidth + linkLeft + lOffset;
        $cluetip.css({left: posX});
      } else {
        posX = (linkWidth > linkLeft && linkLeft > tipWidth)
          || linkLeft + linkWidth + tipWidth + lOffset > winWidth 
          ? linkLeft - tipWidth - lOffset 
          : linkWidth + linkLeft + lOffset;
        if (link.tagName.toLowerCase() == 'area' || opts.positionBy == 'mouse' || linkWidth + tipWidth > winWidth) { // position by mouse
          if (mouseX + 20 + tipWidth > winWidth) {  
            $cluetip.addClass(' cluetip-' + ctClass);
            posX = (mouseX - tipWidth - lOffset) >= 0 ? mouseX - tipWidth - lOffset - parseInt($cluetip.css('marginLeft'),10) + parseInt($cluetipInner.css('marginRight'),10) :  mouseX - (tipWidth/2);
          } else {
            posX = mouseX + lOffset;
          }
        }
        var pY = posX < 0 ? event.pageY + tOffset : event.pageY;
        $cluetip.css({
          left: (posX > 0 && opts.positionBy != 'bottomTop') ? posX : (mouseX + (tipWidth/2) > winWidth) ? winWidth/2 - tipWidth/2 : Math.max(mouseX - (tipWidth/2),0),
          zIndex: $this.data('thisInfo').zIndex
        });
        $cluetipArrows.css({zIndex: $this.data('thisInfo').zIndex+1});
      }
        wHeight = $(window).height();

/***************************************
* load a string from cluetip method's first argument
***************************************/
      if (js) {
        if (typeof js == 'function') {
          js = js(link);
        }
        $cluetipInner.html(js);
        cluetipShow(pY);
      }
/***************************************
* load the title attribute only (or user-selected attribute). 
* clueTip title is the string before the first delimiter
* subsequent delimiters place clueTip body text on separate lines
***************************************/

      else if (tipParts) {
        var tpl = tipParts.length;
        $cluetipInner.html(tipParts[0]);
        if (tpl > 1) {
          for (var i=1; i < tpl; i++){
            $cluetipInner.append('<div class="split-body">' + tipParts[i] + '</div>');
          }          
        }
        cluetipShow(pY);
      }
/***************************************
* load external file via ajax          
***************************************/

      else if (!opts.local && tipAttribute.indexOf('#') != 0) {
        if (/\.(jpe?g|tiff?|gif|png)$/i.test(tipAttribute)) {
          $cluetipInner.html('<img src="' + tipAttribute + '" alt="' + tipTitle + '" />');
          cluetipShow(pY);
        } else if (cluetipContents && opts.ajaxCache) {
          $cluetipInner.html(cluetipContents);
          cluetipShow(pY);
        } else {
          var optionBeforeSend = opts.ajaxSettings.beforeSend,
              optionError = opts.ajaxSettings.error,
              optionSuccess = opts.ajaxSettings.success,
              optionComplete = opts.ajaxSettings.complete;
          var ajaxSettings = {
            cache: false, // force requested page not to be cached by browser
            url: tipAttribute,
            beforeSend: function(xhr) {
              if (optionBeforeSend) {optionBeforeSend.call(link, xhr, $cluetip, $cluetipInner);}
              $cluetipOuter.children().empty();
              if (opts.waitImage) {
                $cluetipWait
                .css({top: mouseY+20, left: mouseX+20, zIndex: $this.data('thisInfo').zIndex-1})
                .show();
              }
            },
            error: function(xhr, textStatus) {
              if (isActive) {
                if (optionError) {
                  optionError.call(link, xhr, textStatus, $cluetip, $cluetipInner);
                } else {
                  $cluetipInner.html('<i>sorry, the contents could not be loaded</i>');  
                }
              }
            },
            success: function(data, textStatus) {       
              cluetipContents = opts.ajaxProcess.call(link, data);
              if (isActive) {
                if (optionSuccess) {optionSuccess.call(link, data, textStatus, $cluetip, $cluetipInner);}
                $cluetipInner.html(cluetipContents);
              }
            },
            complete: function(xhr, textStatus) {
              if (optionComplete) {optionComplete.call(link, xhr, textStatus, $cluetip, $cluetipInner);}
              imgCount = $('#cluetip-inner img').length;
              if (imgCount && !$.browser.opera) {
                $('#cluetip-inner img').bind('load error', function() {
                  imgCount--;
                  if (imgCount<1) {
                    $cluetipWait.hide();
                    if (isActive) cluetipShow(pY);
                  }
                }); 
              } else {
                $cluetipWait.hide();
                if (isActive) { cluetipShow(pY); }
              } 
            }
          };
          var ajaxMergedSettings = $.extend(true, {}, opts.ajaxSettings, ajaxSettings);
          
          $.ajax(ajaxMergedSettings);
        }

/***************************************
* load an element from the same page
***************************************/
      } else if (opts.local) {
        
        var $localContent = $(tipAttribute + (/#\S+$/.test(tipAttribute) ? '' : ':eq(' + index + ')')).clone(true).show();
        $cluetipInner.html($localContent);
        cluetipShow(pY);
      }
    };

// get dimensions and options for cluetip and prepare it to be shown
    var cluetipShow = function(bpY) {
      $cluetip.addClass('cluetip-' + ctClass);
      if (opts.truncate) { 
        var $truncloaded = $cluetipInner.text().slice(0,opts.truncate) + '...';
        $cluetipInner.html($truncloaded);
      }
      function doNothing() {}; //empty function
      tipTitle ? $cluetipTitle.show().html(tipTitle) : (opts.showTitle) ? $cluetipTitle.show().html('&nbsp;') : $cluetipTitle.hide();
      if (opts.sticky) {
        var $closeLink = $('<div id="cluetip-close"><a href="#">' + opts.closeText + '</a></div>');
        (opts.closePosition == 'bottom') ? $closeLink.appendTo($cluetipInner) : (opts.closePosition == 'title') ? $closeLink.prependTo($cluetipTitle) : $closeLink.prependTo($cluetipInner);
        $closeLink.bind('click.cluetip', function() {
          cluetipClose();
          return false;
        });
        if (opts.mouseOutClose) {
          $cluetip.bind('mouseleave.cluetip', function() {
            cluetipClose();
          });
        } else {
          $cluetip.unbind('mouseleave.cluetip');
        }
      }
// now that content is loaded, finish the positioning 
      var direction = '';
      $cluetipOuter.css({zIndex: $this.data('thisInfo').zIndex, overflow: defHeight == 'auto' ? 'visible' : 'auto', height: defHeight});
      tipHeight = defHeight == 'auto' ? Math.max($cluetip.outerHeight(),$cluetip.height()) : parseInt(defHeight,10);   
      tipY = posY;
      baseline = sTop + wHeight;
      if (opts.positionBy == 'fixed') {
        tipY = posY - opts.dropShadowSteps + tOffset;
      } else if ( (posX < mouseX && Math.max(posX, 0) + tipWidth > mouseX) || opts.positionBy == 'bottomTop') {
        if (posY + tipHeight + tOffset > baseline && mouseY - sTop > tipHeight + tOffset) { 
          tipY = mouseY - tipHeight - tOffset;
          direction = 'top';
        } else { 
          tipY = mouseY + tOffset;
          direction = 'bottom';
        }
      } else if ( posY + tipHeight + tOffset > baseline ) {
        tipY = (tipHeight >= wHeight) ? sTop : baseline - tipHeight - tOffset;
      } else if ($this.css('display') == 'block' || link.tagName.toLowerCase() == 'area' || opts.positionBy == "mouse") {
        tipY = bpY - tOffset;
      } else {
        tipY = posY - opts.dropShadowSteps;
      }
      if (direction == '') {
        posX < linkLeft ? direction = 'left' : direction = 'right';
      }
      $cluetip.css({top: tipY + 'px'}).removeClass().addClass('clue-' + direction + '-' + ctClass).addClass(' cluetip-' + ctClass);
      if (opts.arrows) { // set up arrow positioning to align with element
        var bgY = (posY - tipY - opts.dropShadowSteps);
        $cluetipArrows.css({top: (/(left|right)/.test(direction) && posX >=0 && bgY > 0) ? bgY + 'px' : /(left|right)/.test(direction) ? 0 : ''}).show();
      } else {
        $cluetipArrows.hide();
      }

// (first hide, then) ***SHOW THE CLUETIP***
      $dropShadow.hide();
      $cluetip.hide()[opts.fx.open](opts.fx.open != 'show' && opts.fx.openSpeed);
      if (opts.dropShadow) { $dropShadow.css({height: tipHeight, width: tipInnerWidth, zIndex: $this.data('thisInfo').zIndex-1}).show(); }
      if ($.fn.bgiframe) { $cluetip.bgiframe(); }
      // delayed close (not fully tested)
      if (opts.delayedClose > 0) {
        closeOnDelay = setTimeout(cluetipClose, opts.delayedClose);
      }
      // trigger the optional onShow function
      opts.onShow.call(link, $cluetip, $cluetipInner);
    };

/***************************************
   =INACTIVATION
-------------------------------------- */
    var inactivate = function(event) {
      isActive = false;
      $cluetipWait.hide();
      if (!opts.sticky || (/click|toggle/).test(opts.activation) ) {
        cluetipClose();
        clearTimeout(closeOnDelay);        
      };
      if (opts.hoverClass) {
        $this.removeClass(opts.hoverClass);
      }
    };
// close cluetip and reset some things
    var cluetipClose = function() {
      $cluetipOuter 
      .parent().hide().removeClass();
      opts.onHide.call(link, $cluetip, $cluetipInner);
      $this.removeClass('cluetip-clicked');
      if (tipTitle) {
        $this.attr(opts.titleAttribute, tipTitle);
      }
      $this.css('cursor','');
      if (opts.arrows) $cluetipArrows.css({top: ''});
	  if (opts.hoverClass) {
        $this.removeClass(opts.hoverClass);
      }
    };

    $(document).bind('hideCluetip', function(e) {
      cluetipClose();
    });
/***************************************
   =BIND EVENTS
-------------------------------------- */
  // activate by click
      if ( (/click|toggle/).test(opts.activation) ) {
        $this.bind('click.cluetip', function(event) {
          if ($cluetip.is(':hidden') || !$this.is('.cluetip-clicked')) {
            activate(event);
            $('.cluetip-clicked').removeClass('cluetip-clicked');
            $this.addClass('cluetip-clicked');
          } else {
            inactivate(event);
          }
          this.blur();
          return false;
        });
  // activate by focus; inactivate by blur    
      } else if (opts.activation == 'focus') {
        $this.bind('focus.cluetip', function(event) {
          activate(event);
        });
        $this.bind('blur.cluetip', function(event) {
          inactivate(event);
        });
  // activate by hover
      } else {
        // clicking is returned false if clickThrough option is set to false
        $this[opts.clickThrough ? 'unbind' : 'bind']('click', returnFalse);
        //set up mouse tracking
        var mouseTracks = function(evt) {
          if (opts.tracking == true) {
            var trackX = posX - evt.pageX;
            var trackY = tipY ? tipY - evt.pageY : posY - evt.pageY;
            $this.bind('mousemove.cluetip', function(evt) {
              $cluetip.css({left: evt.pageX + trackX, top: evt.pageY + trackY });
            });
          }
        };
        if ($.fn.hoverIntent && opts.hoverIntent) {
          $this.hoverIntent({
            sensitivity: opts.hoverIntent.sensitivity,
            interval: opts.hoverIntent.interval,  
            over: function(event) {
              activate(event);
              mouseTracks(event);
            }, 
            timeout: opts.hoverIntent.timeout,  
            out: function(event) {inactivate(event); $this.unbind('mousemove.cluetip');}
          });           
        } else {
          $this.bind('mouseenter.cluetip', function(event) {
            activate(event);
            mouseTracks(event);
          })
          .bind('mouseleave.cluetip', function(event) {
            inactivate(event);
            $this.unbind('mousemove.cluetip');
          });
        }
        // remove default title tooltip on hover
        $this.bind('mouseenter.cluetip', function(event) {
          $this.attr('title','');
        })
        .bind('mouseleave.cluetip', function(event) {
          $this.attr('title', $this.data('thisInfo').title);
        });
      }
    });
  };
  
/*
 * options for clueTip
 *
 * each one can be explicitly overridden by changing its value. 
 * for example: $.fn.cluetip.defaults.width = 200; 
 * would change the default width for all clueTips to 200. 
 *
 * each one can also be overridden by passing an options map to the cluetip method.
 * for example: $('a.example').cluetip({width: 200}); 
 * would change the default width to 200 for clueTips invoked by a link with class of "example"
 *
 */
  
  $.fn.cluetip.defaults = {  // set up default options
    width:            275,      // The width of the clueTip
    height:           'auto',   // The height of the clueTip
    cluezIndex:       200,       // Sets the z-index style property of the clueTip
    positionBy:       'auto',   // Sets the type of positioning: 'auto', 'mouse','bottomTop', 'fixed'
    topOffset:        15,       // Number of px to offset clueTip from top of invoking element
    leftOffset:       15,       // Number of px to offset clueTip from left of invoking element
    local:            false,    // Whether to use content from the same page for the clueTip's body
    localPrefix:      null,       // string to be prepended to the tip attribute if local is true
    hideLocal:        true,     // If local option is set to true, this determines whether local content
                                // to be shown in clueTip should be hidden at its original location
    attribute:        'rel',    // the attribute to be used for fetching the clueTip's body content
    titleAttribute:   'title',  // the attribute to be used for fetching the clueTip's title
    splitTitle:       '',       // A character used to split the title attribute into the clueTip title and divs
                                // within the clueTip body. more info below [6]
    escapeTitle:      false,    // whether to html escape the title attribute
    showTitle:        true,     // show title bar of the clueTip, even if title attribute not set
    cluetipClass:     'default',// class added to outermost clueTip div in the form of 'cluetip-' + clueTipClass.
    hoverClass:       '',       // class applied to the invoking element onmouseover and removed onmouseout
    waitImage:        true,     // whether to show a "loading" img, which is set in jquery.cluetip.css
    cursor:           'help',
    arrows:           false,    // if true, displays arrow on appropriate side of clueTip
    dropShadow:       true,     // set to false if you don't want the drop-shadow effect on the clueTip
    dropShadowSteps:  6,        // adjusts the size of the drop shadow
    sticky:           false,    // keep visible until manually closed
    mouseOutClose:    false,    // close when clueTip is moused out
    activation:       'hover',  // set to 'click' to force user to click to show clueTip
                                // set to 'focus' to show on focus of a form element and hide on blur
    clickThrough:     false,    // if true, and activation is not 'click', then clicking on link will take user to the link's href,
                                // even if href and tipAttribute are equal
    tracking:         false,    // if true, clueTip will track mouse movement (experimental)
    delayedClose:     0,        // close clueTip on a timed delay (experimental)
    closePosition:    'top',    // location of close text for sticky cluetips; can be 'top' or 'bottom' or 'title'
    closeText:        'Close',  // text (or HTML) to to be clicked to close sticky clueTips
    truncate:         0,        // number of characters to truncate clueTip's contents. if 0, no truncation occurs
    
    // effect and speed for opening clueTips
    fx: {             
                      open:       'show', // can be 'show' or 'slideDown' or 'fadeIn'
                      openSpeed:  ''
    },     

    // settings for when hoverIntent plugin is used             
    hoverIntent: {    
                      sensitivity:  3,
              			  interval:     50,
              			  timeout:      0
    },
    // short-circuit function to run just before clueTip is shown. 
    onActivate:       function(e) {return true;},
    // function to run just after clueTip is shown. 
    onShow:           function(ct, ci){},
    // function to run just after clueTip is hidden.
    onHide:           function(ct, ci){},
    // whether to cache results of ajax request to avoid unnecessary hits to server    
    ajaxCache:        true,  
    // process data retrieved via xhr before it's displayed
    ajaxProcess:      function(data) {
                        data = data.replace(/<(script|style|title)[^<]+<\/(script|style|title)>/gm, '').replace(/<(link|meta)[^>]+>/g,'');
                        return data;
    },                
    // can pass in standard $.ajax() parameters. Callback functions, such as beforeSend, 
    // will be queued first within the default callbacks. 
    // The only exception is error, which overrides the default
    ajaxSettings: {
                      // error: function(ct, ci) { /* override default error callback */ }
                      // beforeSend: function(ct, ci) { /* called first within default beforeSend callback }
                      dataType: 'html'
    },
    debug: false
  };
/*
 * Global defaults for clueTips. Apply to all calls to the clueTip plugin.
 *
 * @example $.cluetip.setup({
 *   insertionType: 'prependTo',
 *   insertionElement: '#container'
 * });
 * 
 * @property
 * @name $.cluetip.setup
 * @type Map
 * @cat Plugins/tooltip
 * @option String insertionType: Default is 'appendTo'. Determines the method to be used for inserting the clueTip into the DOM. Permitted values are 'appendTo', 'prependTo', 'insertBefore', and 'insertAfter'
 * @option String insertionElement: Default is 'body'. Determines which element in the DOM the plugin will reference when inserting the clueTip.
 *
 */
  var insertionType = 'appendTo', insertionElement = 'body';
  $.cluetip.setup = function(options) {
    if (options && options.insertionType && (options.insertionType).match(/appendTo|prependTo|insertBefore|insertAfter/)) {
      insertionType = options.insertionType;
    }
    if (options && options.insertionElement) {
      insertionElement = options.insertionElement;
    }
  };
})(jQuery);
// ================ script_s.js ===========================
var inline_area_to = 0;
var loading_image = '<div align="center" style="padding-top: 10px;"><img src="'+ HTTP +'_layouts/images/loading.gif"/></div>';
var return_pages = 0;
var page_modified = 0;
$j(function(){
	Pages_ActivateSortables();
	Pages_DisableSortables();
	Pages_ActivatePageMouseOver();
	Pages_ActivateColorPicker();
	$j('.inline_field').mouseover(function(){
		$j(this).addClass('inline_field_over');
	}).mouseout(function(){
		$j(this).removeClass('inline_field_over');
	}).focus(function(){
		$j(this).addClass('inline_field_focus');
	}).blur(function(){
		setTimeout("$j('#formContactDetails').submit();",500);
		$j('span.save_form').hide();
		$j(this).removeClass('inline_field_focus');
	}).keydown(function(e){
		key1 = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
		if(key1 == 13){
			$j(this).blur();
		}
	}).keyup(function(e){
		if(lca)	lca = clearTimeout();
		lca = setTimeout("LinesCountAll();",500);
	}).elastic();
	$j('.inline_field3').mouseover(function(){
		$j(this).addClass('inline_field_over');
	}).mouseout(function(){
		$j(this).removeClass('inline_field_over');
	}).focus(function(){
		$j(this).addClass('inline_field_focus');
	}).blur(function(){
		setTimeout("$j('#formContactDetails').submit();",500);
		$j('span.save_form').hide();
		$j(this).removeClass('inline_field_focus');
	}).keydown(function(e){
		key1 = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
		if(key1 == 13){
			$j(this).blur();
		}
	}).keyup(function(e){
		if(lca)	lca = clearTimeout();
		lca = setTimeout("LinesCountAll();",500);
	}).elastic();
	$j('.inline_field2').mouseover(function(){
		$j(this).addClass('inline_field_over');
	}).mouseout(function(){
		$j(this).removeClass('inline_field_over');
	}).focus(function(){
		$j(this).addClass('inline_field_focus');
	}).blur(function(){
		setTimeout("$j('#formContactDetails').submit();",500);
		$j('span.save_form').hide();
		$j(this).removeClass('inline_field_focus');
	}).keyup(function(e){
		if(lca)	lca = clearTimeout();
		lca = setTimeout("LinesCountAll();",500);
	}).elastic();
	if ($j('#formContactDetails').length > 0) {
		$j('#formContactDetails').ajaxForm({
			success: function(response){
				if (response != 'success') {
					// display the error
				}else {
					
				}
			}
		});
	}
	if ($j('#formAbout_Me').length > 0) {
		$j('#formAbout_Me').ajaxForm({
			success: function(response){
				if (response != 'success') {
					// display the error
					alert(response);
				}else {
					setTimeout("link_clicked = false;",750);
				}
			}
		});
	}
	if ($j('#formAboutMe').length > 0) {
		$j('#formAboutMe').ajaxForm({
			success: function(response){
				if (response != 'success') {
					// display the error
					alert(response);
				}else {
					setTimeout("link_clicked = false;",750);
				}
			}
		});
	}
	if ($j('#formAboutMeHistory').length > 0) {
		$j('#formAboutMeHistory').ajaxForm({
			success: function(response){
				if (response) {
					if(response == 'empty')
						AboutMe_HideHistory();
					else{
						update = response.split('|||');
						$j('#questions_items').html(update[0]);
						$j('#more_questions_items').html(update[1]);
						AboutMe_HideHistory();
						AboutMe_activateQuestions();
					}
				}
			}
		});
	}
	if ($j('#formFriendsSay').length > 0) {
		$j('#formFriendsSay').ajaxForm({
			success: function(response){
				if (response != 'success') {
					// display the error
					alert(response);
				}else {
					setTimeout("link_clicked = false;",750);
				}
			}
		});
	}
	if ($j('#formFriendsSayHistory').length > 0) {
		$j('#formFriendsSayHistory').ajaxForm({
			success: function(response){
				if (response) {
					if(response == 'empty')
						FriendsSay_HideHistory();
					else{
						update = response.split('|||');
						$j('#friendssay_items').html(update[0]);
						$j('#more_fs_topics_items').html(update[1]);
						FriendsSay_HideHistory();
						FriendsSay_activateTopics();
					}
				}
			}
		});
	}
	if ($j('#formFriendsSayTopic').length > 0) {
		$j('#formFriendsSayTopic').ajaxForm({
			success: function(response){
				if(response){
					update = response.split('|||');
					PrepareResponse(update[0]);
					if(update[0] == 1){
						$j('#friendssay_items').append(update[1]);
						$j('#new_topic').val('');
						CharacterCountAll();
					}else alert(update[1]);
				}
			}
		});
	}
	if ($j('#formMontagePage').length > 0) {
		$j('#formMontagePage').ajaxForm({
			success: function(response){
				if(response){
					update = response.split('|||');
					PrepareResponse(update[0]);
					if(update[0] == 1){
						page_modified = 0;
						if(return_pages == 1) document.location=HTTP+'pages/';
						else{
							$j('#last_saved').html('Page Saved.');
							setTimeout("$j('#last_saved').html('"+update[1]+"');",20000);
						}
					}else alert(update[1]);
				}
			}
		});
	}
	if ($j('#formPagePage').length > 0) {
		$j('#formPagePage').ajaxForm({
			success: function(response){
				if(response){
					update = response.split('|||');
					PrepareResponse(update[0]);
					if(update[0] == 1){
						page_modified = 0;
						if(return_pages == 1) document.location=HTTP+'pages/';
						else{
							$j('#last_saved').html('Page Saved.');
							setTimeout("$j('#last_saved').html('"+update[1]+"');",20000);
							$j('#page_file').html(update[2]);
						}
					}else alert(update[1]);
				}
			},
			resetForm: true
		});
	}
	if ($j('#formFriendComment').length > 0) {
		$j('#formFriendComment').ajaxForm({
			success: function(response){
				if(response){
					update = response.split('|||');
					PrepareResponse(update[0]);
					if(update[0] == 1){
						$j('#friendscomments_error').html('Comment Sent!');
						$j('#but_new_comment').attr('disabled',true);
						setTimeout("ResetCommentsForm();",2000);
					}else alert(update[1]);
				}
			}
		});
	}
});
function ResetCommentsForm(){
	$j('#formFriendComment').resetForm();
	$j('#but_new_comment').attr('disabled',false);
	$j('#friendscomments_error').html('');
}
function ActivateJcropPreview(x1,y1,x2,y2,ratio,minx,miny){
	if(x1 == x2 && y1 == y2){
		x2++;
		y2++;
	}
	$j('#jcrop_target').Jcrop({
		setSelect: [x1, y1, x2, y2],
		addClass: 'preview',
		aspectRatio: 1/ratio,
		minSize:[minx,miny],
		allowSelect: false,
		allowMove: false,
		allowResize: false
	});
}
function ActivateJcrop(x1,y1,x2,y2,ratio,minx,miny){
	if(x1 == x2 && y1 == y2){
		x2++;
		y2++;
	}
	$j('#jcrop_target').Jcrop({
		setSelect: [x1, y1, x2, y2],
		aspectRatio: 1/ratio,
		minSize:[minx,miny],
		allowSelect: false,
		allowMove: true,
		allowResize: true,
		onChange: showCoords,
		onSelect: showCoords
	});
}
function showCoords(c){
	$j('#crop_x1').val(c.x);
	$j('#crop_y1').val(c.y);
	$j('#crop_x2').val(c.x2);
	$j('#crop_y2').val(c.y2);
	$j('#crop_w').val(c.w);
	$j('#crop_h').val(c.h);
}
function AjaxForms(){
	if ($j('#formMail').length > 0) {
		$j('#formMail').ajaxForm({
			success: function(response){
				if(response == 'stepped email'){
					document.location = HTTP + 'editor/?stepped_emails';
				}
				else if (response != 'E-mail successfully sent') {
					$j('#right_side').html(response);
				}
				else {
					$j('#right_side').html('');
					self.parent.tb_remove();
				}
			}
		});
		$j('#formMail').submit(function(){
			$j('#right_side').html('<img align="absmiddle" src="'+ HTTP +'_layouts/images/loading.gif" />&nbsp;&nbsp;<span style="color: #000000;">Please wait... Sending message(s).</span>');
		})
	}
	if ($j("#due_date").length > 0) {
		$j("#due_date").datepicker({
					changeFirstDay: false,
					dateFormat: 'dd/mm/yy',
					showOn: 'both',
					buttonImage: HTTP+'_layouts/images/calendar1.gif',
					buttonImageOnly: true,
					yearRange: '1930:2030',
					defaultDate: new Date()
				});
		}
	if ($j('#formShowPhotoComment').length > 0) {
		$j('#formShowPhotoComment').ajaxForm({
			success: function(response){
				if(response){
					update = response.split('|||');
					PrepareResponse(update[0]);
					if(update[0] == 1){
						$j('#div_comments').prepend(update[1]);
					}else alert(update[1]);
				}
			},
			resetForm: true
		});
	}
	if ($j('#formApplyCropCoords').length > 0) {
		$j('#formApplyCropCoords').ajaxForm({
			success: function(response){
				if(response){
					update = response.split('|||');
					PrepareResponse(update[0]);
					if(update[0] == 1){
						SelectProfilePhoto(update[1],update[2]);
					}else alert(update[1]);
				}
			}
		});
	}
	if ($j('#formAddSection').length > 0) {
		$j('#formAddSection').ajaxForm({
			success: function(response){
				if(response){
					update = response.split('|||');
					PrepareResponse(update[0]);
					if(update[0] == 1){
						$j('#sortable').append(update[1]);
						Pages_RefreshSortables();
						tb_remove();
					}else alert(update[1]);
				}
			}
		});
	}
	if ($j('#formAddPage').length > 0) {
		$j('#formAddPage').ajaxForm({
			success: function(response){
				if(response){
					update = response.split('|||');
					PrepareResponse(update[0]);
					if(update[0] == 1){
						var s_id = update[1];
						$j('.section_details').slideUp();
						$j('#secdet_'+s_id).slideDown();
						$j('#page_sortables'+s_id).append(update[2]);
						Pages_ActivatePageMouseOver();
						Pages_ActivateSectionClick();
						if(update[3]){
							$j('#page_suggestion'+update[3]).remove();
							$j('.suggestions_sep'+update[3]).remove();
						}
						tb_remove();
					}else alert(update[1]);
				}
			}
		});
	}
	if ($j('#formModifyPage').length > 0) {
		$j('#formModifyPage').ajaxForm({
			success: function(response){
				if(response){
					update = response.split('|||');
					PrepareResponse(update[0]);
					if(update[0] == 1){
						tb_remove();
						$j('#page_section_name').html(update[2]);
						$j('#page_page_name').html(update[1]);
					}else alert(update[1]);
				}
			}
		});
	}
	if ($j('#formSubmitPage').length > 0) {
		$j('#formSubmitPage').ajaxForm({
			success: function(response){
				if(response){
					update = response.split('|||');
					PrepareResponse(update[0]);
					if(update[0] == 1){
						alert(update[1]);
						tb_remove();
						document.location=HTTP+'pages/';
					}else alert(update[1]);
				}
			}
		});
	}
	if ($j('#formAddSuggestion').length > 0) {
		$j('#formAddSuggestion').ajaxForm({
			success: function(response){
				if(response){
					update = response.split('|||');
					PrepareResponse(update[0]);
					if(update[0] == 1){
						alert(update[1]);
						tb_remove();
					}else alert(update[1]);
				}
			}
		});
	}
	if ($j('#formReqTransfer').length > 0) {
		$j('#formReqTransfer').ajaxForm({
			success: function(response){
				if(response){
					update = response.split('|||');
					PrepareResponse(update[0]);
					if(update[0] == 1){
						alert(update[1]);
						location.reload();
					}else alert(update[1]);
				}
			}
		});
	}
	if ($j('#formSimpleUpload').length > 0) {
		$j('#formSimpleUpload').ajaxForm({
			success: function(response){
				update = response.split('|||');
				PrepareResponse(update[0]);
				if(update[0] == 1){
					if(update[1] == 'success'){
						photo_id = update[2];
						index = update[3];
						ratio = update[4];
						tb_show(false,HTTP+'photos/?crop_photo='+photo_id+'&index='+index+'&type=profile&crop_ratio='+ratio+'&resize=true&height=570&width=842&modal=true',false);
					}else if(update[1] == 'montage'){
						photo_id = update[2];
						index = update[3];
						ratio = update[4];
						tb_show(false,HTTP+'photos/?crop_photo='+photo_id+'&index='+index+'&type=montage&crop_ratio='+ratio+'&resize=true&height=570&width=842&modal=true',false);
					}else if(update[1] == 'new'){
						page_modified = 1;
						$j('#but_add_photo').before(update[2]);
						nr_photos = $j('#now_photos').val();
						nr_photos++;
						max_photos = $j('#max_photos_total').val();
						if(nr_photos < max_photos){
						}else $j('#but_add_photo').hide();
						$j('#now_photos').val(nr_photos);
						is_cap = $j('#caption').val();
						if(is_cap != 1){
							$j('.link_caption').addClass('hidden');
						}
						tb_remove();
					}else if(update[1] == 'polls'){
						page_modified = 1;
						$j('#photo_item'+update[2]).html(update[3]);
						tb_remove();
					}else if(update[1] == 'author'){
						page_modified = 1;
						$j('#author_photoname').html(update[2]);
						$j('#but_author_photo').attr('value','Change...');
						tb_remove();
					}else{
						page_modified = 1;
						$j('#photo_src'+update[1]).remove();
						$j('#photo_item'+update[1]).prepend(update[2]);
						tb_remove();
					}
					
				}else $j('#right_side').html(update[1]);
			}
		});
	}
}
function ActivateMultipleSpelling(){
	var googie5 = new GoogieSpellMultiple(HTTP+"_layouts/js/googiespell/", HTTP+"sendReq.php?lang=");
    //New menu item "Add"
    var add_checker = function(elm) {
      return true;
    };
    var add_item = function(elm, current_googie) {
      googie5.ignoreAll(elm);
    };
    googie5.appendNewMenuItem("Add", add_item, add_checker);
    var fn_no_more_errors = function(e) {
      alert('no more errros');
    }
    googie5.setDependent();
//    googie5.setCustomAjaxError(function(req) {
//      alert("Error:" +req.value);
//    });
    googie5.useCloseButtons();
    googie5.noMoreErrorsCallback(fn_no_more_errors);
    googie5.setSpellContainer("global_spell_container");
    // activate the spelling feature for the Questions section
    if($j('form#formAboutMe').length > 0)
	$j('form#formAboutMe textarea').each(function(){
		area_id = $j(this).attr('id');
		googie5.decorateTextareas(area_id);
	});
	// activate the spelling feature for the Friends Say section
	if($j('form#formFriendsSay').length > 0)
	$j('form#formFriendsSay textarea').each(function(){
		area_id = $j(this).attr('id');
		googie5.decorateTextareas(area_id);
	});
	// activate the spelling feature for the Friends Comments section
	if($j('#formFriendsComments').length > 0){
		$j('form#formFriendsComments textarea').each(function(){
			area_id = $j(this).attr('id');
			googie5.decorateTextareas(area_id);
		});
	}
	// Apply Spelling for About Me section
	if($j('#about_me').length > 0)
    googie5.decorateTextareas("about_me");
}
function ActivateSpelling(){
	var googie1 = new GoogieSpell(HTTP+"_layouts/js/googiespell/", HTTP+"sendReq.php?lang=");
	googie1.decorateTextarea("question_19");
}
function About_Me_activate(){
	$j('.inline_aboutme').mouseover(function(){
		$j(this).addClass('inline_field_over');
	}).mouseout(function(){
		$j(this).removeClass('inline_field_over');
	}).focus(function(){
		$j(this).addClass('inline_field_focus');
		if($j(this).val() == $j('#aboutme_default').val()){
			$j(this).val('');
			$j(this).removeClass('grayText');
		}
	}).blur(function(){
		if($j(this).val() == ''){
			$j(this).val($j('#aboutme_default').val());
			$j(this).addClass('grayText');
			$j(this).keyup();
		}
		setTimeout("$j('#aboutme_actions').hide();",100);
		$j(this).removeClass('inline_field_focus');
	}).keyup(function(e){
		if(lca)	lca = clearTimeout();
		lca = setTimeout("LinesCountAll();",500);
	}).elastic().live('input paste',function(e){ setTimeout( "LinesCountAll();", 250); });
}
function AboutMe_activateQuestions(){
	$j('.inline_area').mouseover(function(){
		$j(this).addClass('inline_field_over');
	}).mouseout(function(){
		$j(this).removeClass('inline_field_over');
	}).focus(function(){
		$j(this).addClass('inline_field_focus');
	}).blur(function(){
		idd = $j(this).attr('id').substr(9);
		setTimeout("$j('#question_actions"+idd+"').hide();",100);
		$j(this).removeClass('inline_field_focus');
	}).keyup(function(e){
		if(lca)	lca = clearTimeout();
		lca = setTimeout("LinesCountAll();",500);
	}).elastic().live('input paste',function(e){ setTimeout( "LinesCountAll();", 250); });
}
function AboutMe_InsertNewQuestion(id,user_id){
	$j.post(HTTP + 'profiles/insert_new_question/' + id, 
	{user_id: user_id}, function (response) {
		if(response){
			update = response.split('|||');
			PrepareResponse(update[0]);
			if(update[0] == 1){
				$j('#questions_items').append(update[1]);
				$j('#more_question_'+id).remove();
				LinesCountAll();
			}else alert(update[1]);
		}
	});
}
function AboutMe_RemoveQuestion(id,user_id){
	$j.post(HTTP + 'profiles/remove_question/' + id, 
	{user_id: user_id}, function (response) {
		if(response){
			update = response.split('|||');
			PrepareResponse(update[0]);
			if(update[0] == 1){
				$j('#more_questions_items').append(update[1]);
				$j('#about_me_item'+id).remove();
				LinesCountAll();
				setTimeout("link_clicked = false;",750);
			}else alert(update[1]);
		}
	});
}
function AboutMe_DisplayHistory(idx,user_id){
	if(idx){
		$j('form#formAboutMe').css('display','none');
		$j('#history_questions_items').load(HTTP+'profiles/load_history/'+idx+'/'+user_id);
	}
}
function AboutMe_ShowHistory(){
	$j('form#formAboutMeHistory').show('slow');
}
function AboutMe_HideHistory(){
	$j('#history_questions_items').html('');
	$j('#history_idx').val('');
	$j('form#formAboutMe').show();
	$j('form#formAboutMeHistory').hide('slow');
}
function CopyQuestionText(q_id){
	$j('#cancel_qtext_'+q_id).val($j('#question_'+q_id).val());
}
function RestoreQuestionText(q_id){
	$j('#question_'+q_id).val($j('#cancel_qtext_'+q_id).val());
	$j('#question_'+q_id).keyup();
	setTimeout("link_clicked = false;",750);
}
function CopyAboutMeText(){
	$j('#aboutme_cancel').val($j('#about_me').val());
}
function RestoreAboutMeText(){
	$j('#about_me').val($j('#aboutme_cancel').val());
	$j('#about_me').keyup();
	if($j('#about_me').val() == $j('#aboutme_default').val())
		$j('#about_me').addClass('grayText');
	setTimeout("link_clicked = false;",750);
}
function CopyFSTopicText(q_id){
	$j('#cancel_topictext_'+q_id).val($j('#fs_topic_'+q_id).val());
}
function RestoreFSTopicText(q_id){
	$j('#fs_topic_'+q_id).val($j('#cancel_topictext_'+q_id).val());
	$j('#fs_topic_'+q_id).keyup();
	setTimeout("link_clicked = false;",750);
}
function CopyFCommText(q_id){
	$j('#cancel_commtext_'+q_id).val($j('#friend_comment_'+q_id).val());
}
function RestoreFCommText(q_id){
	$j('#friend_comment_'+q_id).val($j('#cancel_commtext_'+q_id).val());
	$j('#friend_comment_'+q_id).keyup();
	setTimeout("link_clicked = false;",750);
}
function FriendsComm_saveComment(id,user_id){
	text = $j('#friend_comment_'+id).val();
	$j.post(HTTP + 'profiles/save_comment/' + id, 
	{message: text, user_id: user_id}, function (response) {		
		if(response){
			update = response.split('|||');
			PrepareResponse(update[0]);
			if(update[0] == 1){
				setTimeout("link_clicked = false;",750);
			}else alert(update[1]);
		}
	});
}
function FriendsComm_deleteComment(id){
	$j.post(HTTP + 'profiles/delete_comment/' + id, 
	{}, function (response) {		
		if(response){
			update = response.split('|||');
			PrepareResponse(update[0]);
			if(update[0] == 1){
				$j('#friends_comm_item'+id).remove();
				LinesCountAll();
				setTimeout("link_clicked = false;",750);
			}else alert(update[1]);
		}
	});
}
function FriendsComm_includeComment(id){
	var check = 0;
	if($j('#fcomm_include_' + id + ':checked').length > 0){
		// include comment
		check = 1;
	}else{
		// remove comment
		check = 2;
	}
	$j.post(HTTP + 'profiles/include_comment/' + id + '/', 
	{mode: check}, function(response){
		if (response) {
			update = response.split('|||');
			PrepareResponse(update[0]);
			if(update[0] == 1){
				LinesCountAll();
			}else alert(update[1]);
		}
	});
}
lca = 0;
function FriendsComm_activateComments(){
	$j('.inline_comment').mouseover(function(){
		$j(this).addClass('inline_field_over');
	}).mouseout(function(){
		$j(this).removeClass('inline_field_over');
	}).focus(function(){
		$j(this).addClass('inline_field_focus');
	}).blur(function(){
		idd = $j(this).attr('id').substr(15);
		setTimeout("$j('#fcomm_actions"+idd+"').hide();",100);
		$j(this).removeClass('inline_field_focus');
		if(!link_clicked){
			FriendsComm_saveComment(idd);
		}
	}).keyup(function(e){
		if(lca)	lca = clearTimeout();
		lca = setTimeout("LinesCountAll();",500);
	}).elastic().live('input paste',function(e){ setTimeout( "LinesCountAll();", 250); });
}
function FriendsSay_InsertNewTopic(id,user_id){
	$j.post(HTTP + 'profiles/insert_new_topic/' + id, 
	{user_id: user_id}, function (response) {
		if(response){
			update = response.split('|||');
			PrepareResponse(update[0]);
			if(update[0] == 1){
				$j('#friendssay_items').append(update[1]);
				$j('#more_topics_'+id).remove();
				LinesCountAll();
			}else alert(update[1]);
		}
	});
}
function FriendsSay_RemoveTopic(id,user_id){
	$j.post(HTTP + 'profiles/remove_topic/' + id, 
	{user_id: user_id}, function (response) {
		if(response){
			update = response.split('|||');
			PrepareResponse(update[0]);
			if(update[0] == 1){
				if(update[1] != 'deleted')
				$j('#more_fs_topics_items').append(update[1]);
				$j('#friends_say_item'+id).remove();
				LinesCountAll();
				setTimeout("link_clicked = false;",750);
			}else alert(update[1]);
		}
	});
}
function FriendsSay_DisplayHistory(idx,user_id){
	if(idx){
		$j('form#formFriendsSay').css('display','none');
		$j('#history_friendssay_items').load(HTTP+'profiles/load_fs_history/'+idx+'/'+user_id);
	}
}
function FriendsSay_ShowHistory(){
	$j('form#formFriendsSayHistory').show('slow');
}
function FriendsSay_HideHistory(){
	$j('#history_friendssay_items').html('');
	$j('form#formFriendsSay').show();
	$j('#fs_history_idx').val('');
	$j('form#formFriendsSayHistory').hide('slow');
}
function FriendsSay_activateTopics(){
	$j('.inline_topic').mouseover(function(){
		$j(this).addClass('inline_field_over');
	}).mouseout(function(){
		$j(this).removeClass('inline_field_over');
	}).focus(function(){
		if($j(this).val() == '') $j(this).val('- ');
		$j(this).addClass('inline_field_focus');
	}).blur(function(){
		if($j(this).val() == '- ') $j(this).val('');
		idd = $j(this).attr('id').substr(9);
		setTimeout("$j('#fs_topic_actions"+idd+"').hide();",100);
		$j(this).removeClass('inline_field_focus');
	}).keyup(function(e){
		key1 = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
		if(key1 == 13){
			var val = $j(this).val();
			val = val.split('- ').join('');
			val = '- '+ val.split('\n').join('\n- ');
			$j(this).val(val);
		}
		if(lca)	lca = clearTimeout();
		lca = setTimeout("LinesCountAll();",500);
	}).elastic();
}
function FriendsSay_includeTopic(id,user_id){
	var check = 0;
	if($j('#fs_include_' + id + ':checked').length > 0){
		// include topic
		check = 1;
	}else{
		// remove topic
		check = 2;
	}
	$j.post(HTTP + 'profiles/include_topic/' + id + '/'+user_id, 
	{mode: check}, function(response){
		if (response) {
			update = response.split('|||');
			PrepareResponse(update[0]);
			if(update[0] == 1){
				LinesCountAll();
			}else alert(update[1]);
		}
	});
}
function PrepareResponse(txt){
	if (txt.length > 1) {
		alert("AJAX Response Error: "+txt.substr(0,txt.length-1));
		txt = txt.substr(-1);
	}
}
function LinesCountAll(){
	all_text = '';
	all_lines = 0;
	details_lines = 0;
	aboutme_lines = 0;
	fs_lines = 0;
	fcom_lines = 0;
	qs_lines = 0;
	var mode = 1;
	// Count Lines for the Details section 
	if($j('form#formContactDetails').length>0){
		$j('form#formContactDetails textarea').each(function(){
			if($j(this).val() != ''){
			xx = $j(this).parent().children('div.twin').height();
			details_lines += xx/16;
			}
		});
		if($j('#dob').length>0) details_lines += 1;
	}
	// Count lines for the Questions section
	if($j('form#formAboutMe').length>0){
	$j('form#formAboutMe textarea').each(function(){
		q_height = $j(this).parent().children('div.row_name_line').height();
		xx = $j(this).parent().children('div.twin').height();
		qs_lines += xx/16;
		qs_lines += q_height/16 + 1;
	});
	}
	// Count lines for the About Me section
	if($j('form#formAbout_Me').length>0){
		$j('form#formAbout_Me textarea').each(function(){
			if($j(this).val() != $j('#aboutme_default').val()){
			xx = $j(this).parent().children('div.twin').height();
			aboutme_lines += xx/16; // the height of the textarea.
			}
		});
	}
	// Count lines for the Friends Say section
	if($j('form#formFriendsSay').length>0){
		$j('form#formFriendsSay textarea').filter(filter_textarea).each(function(){
			q_height = $j(this).parent().children('div.row_name_line').height();
			xx = $j(this).parent().children('div.twin').height();
			fs_lines += xx/16;
			fs_lines += q_height/16 + 1;		
		});
	}
	// Count lines for the Friends Comments section
	if($j('form#formFriendsComments').length>0){
		$j('form#formFriendsComments textarea').filter(filter_textarea_comm).each(function(){
			xx = $j(this).parent().children('div.twin').height();
			fcom_lines += xx/16; // the lines of the comment
			fcom_lines += 2; // 1 for the author and 1 for the space between comments
		});
	}
	limit_error = false;
	$j('.counter_item').each(function(){
		all_lines = 0;
		if($j(this).hasClass('count_details')){
			all_lines += details_lines;
		}
		if($j(this).hasClass('count_about_me')){
			all_lines += aboutme_lines;
		}
		if($j(this).hasClass('count_questions')){
			all_lines += qs_lines;
		}
		if($j(this).hasClass('count_fs')){
			all_lines += fs_lines;
		}
		if($j(this).hasClass('count_fcomm')){
			all_lines += fcom_lines;
		}
		limit = parseInt($j(this).children('.myCounter_limit').html());
		$j(this).children('.myCounter').html(all_lines);
		if(all_lines > limit){
			limit_error = true;
			$j(this).children('.myCounter').addClass('redText');
			$j(this).children('.myCounter_name').addClass('redText');
		}else{
			$j(this).children('.myCounter').removeClass('redText');
			$j(this).children('.myCounter_name').removeClass('redText');
		}
	});
	if(limit_error){
		$j('#counterBox').addClass('textBlock_red');
		$j('#counterWarn').show();
	}else{
		$j('#counterBox').removeClass('textBlock_red');
		$j('#counterWarn').hide();
	}
}
function CharacterCountAll(){
	var all_text = '';
	var all_length = 0;
	var limit = parseInt($j('#about_me_total').html());
	$j('form#formAboutMe textarea').each(function(){
		all_text += $j(this).val();
		all_length += $j(this).val().length;
		all_length += 100;
	});
	// filter is used to know if the topic is included in the Friends Say... section
	$j('form#formFriendsSay textarea').filter(filter_textarea).each(function(){
		all_text += $j(this).val();
		all_length += $j(this).val().length;
		all_length += 100;
	});
	$j('#myCounter').html(all_length);
	if(all_length > limit){
		$j('#myCounter').addClass('redText');
		$j('#counterBox').addClass('textBlock_red');
		$j('#counterWarn').show();
	}else {
		$j('#myCounter').removeClass('redText');
		$j('#counterBox').removeClass('textBlock_red');
		$j('#counterWarn').hide();
	}
}
function filter_textarea(){
	var name = $j(this).attr('id');
	return include_textarea(name);
}
function include_textarea(name){
	tp = name.substr(9);
	if ($j('#fs_include_' + tp).length == 0) return true;
	return ($j('#fs_include_' + tp + ':checked').length > 0);
}
function filter_textarea_comm(){
	var name = $j(this).attr('id');
	return include_textarea_comm(name);
}
function include_textarea_comm(name){
	tp = name.substr(15);
	if ($j('#fcomm_include_' + tp).length == 0) return true;
	return ($j('#fcomm_include_' + tp + ':checked').length > 0);
}
function FriendsSay_ViewactivateTopics(){
	$j('.inline_topic').mouseover(function(){
		$j(this).addClass('inline_field_over');
	}).mouseout(function(){
		$j(this).removeClass('inline_field_over');
	}).focus(function(){
		if($j(this).val() == '') $j(this).val('- ');
		$j(this).addClass('inline_field_focus');
	}).blur(function(){
		if($j(this).val() == '- ') $j(this).val('');
		idd = $j(this).attr('id').substr(9);
		setTimeout("$j('#fs_topic_actions"+idd+"').hide();",100);
		$j(this).removeClass('inline_field_focus');
	}).keyup(function(e){
		key1 = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
		if(key1 == 13){
			var val = $j(this).val();
			val = val.split('- ').join('');
			val = '- '+ val.split('\n').join('\n- ');
			$j(this).val(val);
		}
	}).elastic();
}
function Pages_ActivatePagesSortables(id){
	if($j("#page_sortables"+id).length > 0)
	$j("#page_sortables"+id).sortable({
		placeholder: 'place_holder_page'
		,forcePlaceholderSize: true
	});
}
function Pages_EnablePagesSortables(id){
	$j('.section_item').each(function(){
		$j(this).unbind('mouseup');		
	});
	$j('.save_page_order').attr('class', 'save_page_order');
	$j('.change_page_order').attr('class', 'change_page_order hidden');
	$j('.section_hash').addClass('selection_tool');
	$j("#page_sortables"+id).sortable('enable');
	$j('.section_page_item_blue').attr('class', 'section_page_item section_page_item_blue hidden');
}
function Pages_DisablePagesSortables(id){
	$j('.change_page_order').attr('class', 'change_page_order');
	$j('.save_page_order').attr('class', 'save_page_order hidden');
	$j("#page_sortables"+id).sortable('disable');
	$j('.section_hash').removeClass('selection_tool');
	if(link_clicked)
		Pages_ActivateSectionClick();
	$j('.section_page_item_blue').attr('class', 'section_page_item section_page_item_blue');
}
function Pages_ActivateSortables(){
	if($j("#sortable").length > 0)
	$j("#sortable").sortable({
		placeholder: 'place_holder'
	});
}
function Pages_EnableSortables(){
	Pages_DectivateSectionClick();
	$j('#save_order').attr('class', '');
	$j('#change_order').attr('class', 'hidden');
	$j('#sections_items').addClass('selection_tool');
	$j("#sortable").sortable('enable');
}
function Pages_DisableSortables(){
	$j('#change_order').attr('class', '');
	$j('#save_order').attr('class', 'hidden');
	$j("#sortable").sortable('disable');
	$j('#sections_items').removeClass('selection_tool');
	Pages_ActivateSectionClick();
}
function Pages_SaveSectionOrder(){
	var ss = $j("#sortable").sortable('serialize');
	$j.post(HTTP + 'pages/save_sections_order?' + ss + '', 
	{}, function(response){
		if (response) {
			if(response == 'success'){
				Pages_DisableSortables();
			}else alert(response);
		}
	});
}
function Pages_SavePageOrder(id){
	var ss = $j("#page_sortables"+id).sortable('serialize');
	$j.post(HTTP + 'pages/save_pages_order?section_id=' + id + '&' + ss + '', 
	{}, function(response){
		if (response) {
			if(response == 'success'){
				Pages_DisablePagesSortables();
				link_clicked = 0;
			}else alert(response);
		}
	});
}
function Pages_DectivateSectionClick(){
	$j('.section_details').slideUp();
	$j('.secact').css('display','none');
	$j('.section_item').each(function(){
		$j(this).unbind('mouseup');		
	});
}
var link_clicked = 0;
function Pages_ActivateSectionClick(){
	$j('.section_item').each(function(){
		$j(this).unbind('mouseup').bind('mouseup',function(){
			if(link_clicked == 1){
				link_clicked = 0;
			}else{
				if($j('#secdet_'+$j(this).attr('id').substr(7)).css('display') == 'block'){
					$j('#secdet_'+$j(this).attr('id').substr(7)).slideUp();
					$j('#secact_'+$j(this).attr('id').substr(7)).css('display','none');
					$j('#secsub_'+$j(this).attr('id').substr(7)).removeClass('section_subheading_ext');
				}else{
					$j('.section_details').slideUp();
					$j('.secact').css('display','none');
					$j('.section_subheading').removeClass('section_subheading_ext');
					$j('#secdet_'+$j(this).attr('id').substr(7)).slideDown();
					$j('#secact_'+$j(this).attr('id').substr(7)).css('display','');
					$j('#secsub_'+$j(this).attr('id').substr(7)).addClass('section_subheading_ext');
				}
			}
		});		
	});
	$j('.section_item a').each(function(){
		$j(this).unbind('mousedown').bind('mousedown',function(){
			link_clicked = 1;
		});
	});
}
function Pages_ActivatePageMouseOver(){
	$j('.section_page_item').each(function(){
		$j(this).unbind('mouseover').bind('mouseover',function(){
			$j(this).children('div').children('div').children('.section_page_links').removeClass('hidden');
		});
		$j(this).unbind('mouseout').bind('mouseout',function(){
			$j(this).children('div').children('div').children('.section_page_links').addClass('hidden');
		});
	});
}
function Pages_DeletePage(id){
	$j.post(HTTP + 'pages/delete_page/'+id + '/', 
	{}, function(response){
		if (response) {
			if(response == 'success'){
				$j('#section_page_'+id).remove();
				//$j("#sortable").sortable('refresh');
			}else alert(response);
		}
	});
}
function Pages_DeleteSection(id){
	$j.post(HTTP + 'pages/delete_section/'+id + '/', 
	{}, function(response){
		if (response) {
			if(response == 'success'){
				$j('#section_'+id).remove();
				//$j("#sortable").sortable('refresh');
			}else alert(response);
		}
	});
}
function Pages_TurnOffSuggestion(id){
	$j.post(HTTP + 'pages/turn_off_suggestion/'+id + '/', 
	{}, function(response){
		if (response) {
			if(response == 'success'){
				$j('#suggestion_'+id).remove();
			}else alert(response);
		}
	});
}
function Pages_SectionHeaderTypeChanged(val){
	if(val == 1){
		$j('#header_type_2').attr('class','field_row hidden');
		$j('#header_type_3').attr('class','field_row hidden');
	}else if(val == 2){
		$j('#header_type_2').attr('class','field_row');
		$j('#header_type_3').attr('class','field_row hidden');
	}else if(val == 3){
		$j('#header_type_2').attr('class','field_row');
		$j('#header_type_3').attr('class','field_row');
	}
}
function Pages_RefreshSortables(){
	$j('#sortable').sortable('refresh');
	Pages_DisableSortables();
}
function Pages_ActivateColorPicker(){
	if($j('#color').length>0)
	$j('#color').ColorPicker({
		onSubmit: function(hsb, hex, rgb, el) {
			$j(el).val(hex);
			$j(el).ColorPickerHide();
		},
		onBeforeShow: function () {
			$j(this).ColorPickerSetColor(this.value);
		}
	})
	.bind('keyup', function(){
		$j(this).ColorPickerSetColor(this.value);
	});
}
function Suggestions_ArticleClicked(){
	$j('#icon_article').attr('class','page_type_icon page_type_icon_sel');
	$j('#article_text').attr('class','');
	$j('#article_example').attr('class','');
	$j('#icon_page').attr('class','page_type_icon');
	$j('#page_text').attr('class','hidden');
	$j('#page_example').attr('class','hidden');
	$j('#icon_montage').attr('class','page_type_icon');
	$j('#type').attr('value','article');
}
function Suggestions_PageClicked(){
	$j('#icon_article').attr('class','page_type_icon');
	$j('#article_text').attr('class','hidden');
	$j('#article_example').attr('class','hidden');
	$j('#icon_page').attr('class','page_type_icon page_type_icon_sel');
	$j('#page_text').attr('class','');
	$j('#page_example').attr('class','');
	$j('#icon_montage').attr('class','page_type_icon');
	$j('#type').attr('value','page');
}
function Suggestions_MontageClicked(){
	$j('#icon_article').attr('class','page_type_icon');
	$j('#article_text').attr('class','hidden');
	$j('#article_example').attr('class','hidden');
	$j('#icon_page').attr('class','page_type_icon');
	$j('#page_text').attr('class','hidden');
	$j('#page_example').attr('class','hidden');
	$j('#icon_montage').attr('class','page_type_icon page_type_icon_sel');
	$j('#type').attr('value','montage');
}

function NewPage_ArticleClicked(){
	$j('#icon_article').attr('class','page_type_icon page_type_icon_sel');
	$j('#icon_page').attr('class','page_type_icon');
	$j('#icon_montage').attr('class','page_type_icon');
	$j('#icon_other').attr('class','page_type_icon');
	$j('#type').attr('value','article');
	$j('#new_page_content').load(HTTP + 'pages/new_page_article_clicked/',function(){
		$j('#new_page_content').attr('class','');
		AjaxForms();
	});
}
function NewPage_PageClicked(){
	$j('#icon_article').attr('class','page_type_icon');
	$j('#icon_page').attr('class','page_type_icon page_type_icon_sel');
	$j('#icon_montage').attr('class','page_type_icon');
	$j('#icon_other').attr('class','page_type_icon');
	$j('#type').attr('value','page');
	$j('#new_page_content').load(HTTP + 'pages/new_page_page_clicked/',function(){
		$j('#new_page_content').attr('class','');
		AjaxForms();
	});
}
function NewPage_MontageClicked(){
	$j('#icon_article').attr('class','page_type_icon');
	$j('#icon_page').attr('class','page_type_icon');
	$j('#icon_montage').attr('class','page_type_icon page_type_icon_sel');
	$j('#icon_other').attr('class','page_type_icon');
	$j('#type').attr('value','montage');
	$j('#new_page_content').load(HTTP + 'pages/new_page_montage_clicked/',function(){
		AjaxForms();
		$j('#new_page_content').attr('class','');
	});
}
function NewPage_OtherClicked(){
	$j('#icon_article').attr('class','page_type_icon');
	$j('#icon_page').attr('class','page_type_icon');
	$j('#icon_montage').attr('class','page_type_icon');
	$j('#icon_other').attr('class','page_type_icon page_type_icon_sel');
	$j('#type').attr('value','other');
	$j('#new_page_content').load(HTTP + 'pages/new_page_other_clicked/',function(){
		AjaxForms();
		$j('#new_page_content').attr('class','');
	});
}
function NewPage_IntroClicked(){
	$j('#icon_intro').attr('class','page_type_icon page_type_icon_sel');
	$j('#icon_polls').attr('class','page_type_icon');
	$j('#icon_index').attr('class','page_type_icon');
	$j('#icon_contents').attr('class','page_type_icon');
	$j('#icon_ends').attr('class','page_type_icon');
	$j('#type').attr('value','intro');
	$j('#other_page_content').load(HTTP + 'pages/new_page_intro_clicked/',function(){
		AjaxForms();
		$j('#other_page_content').attr('class','');
	});
}
function NewPage_PollsClicked(){
	$j('#icon_intro').attr('class','page_type_icon');
	$j('#icon_polls').attr('class','page_type_icon page_type_icon_sel');
	$j('#icon_index').attr('class','page_type_icon');
	$j('#icon_contents').attr('class','page_type_icon');
	$j('#icon_ends').attr('class','page_type_icon');
	$j('#type').attr('value','polls');
	$j('#other_page_content').load(HTTP + 'pages/new_page_polls_clicked/',function(){
		AjaxForms();
		$j('#other_page_content').attr('class','');
	});
}
function NewPage_IndexClicked(){
	$j('#icon_intro').attr('class','page_type_icon');
	$j('#icon_polls').attr('class','page_type_icon');
	$j('#icon_index').attr('class','page_type_icon page_type_icon_sel');
	$j('#icon_contents').attr('class','page_type_icon');
	$j('#icon_ends').attr('class','page_type_icon');
	$j('#type').attr('value','index');	
	$j('#other_page_content').load(HTTP + 'pages/new_page_index_clicked/',function(){
		AjaxForms();
		$j('#other_page_content').attr('class','');
	});
}
function NewPage_ContentsClicked(){
	$j('#icon_intro').attr('class','page_type_icon');
	$j('#icon_polls').attr('class','page_type_icon');
	$j('#icon_index').attr('class','page_type_icon');
	$j('#icon_contents').attr('class','page_type_icon page_type_icon_sel');
	$j('#icon_ends').attr('class','page_type_icon');
	//$j('#type').attr('value','intro');	
}
function NewPage_EndsClicked(){
	$j('#icon_intro').attr('class','page_type_icon');
	$j('#icon_polls').attr('class','page_type_icon');
	$j('#icon_index').attr('class','page_type_icon');
	$j('#icon_contents').attr('class','page_type_icon');
	$j('#icon_ends').attr('class','page_type_icon page_type_icon_sel');
	$j('#type').attr('value','blank');
	$j('#other_page_content').load(HTTP + 'pages/new_page_ends_clicked/',function(){
		AjaxForms();
		$j('#other_page_content').attr('class','');
	});
}
function NewPage_TemplateClicked(id,val){
	$j('.template_icon').attr('class','template_icon page_type_icon');
	$j('#icon_template'+id).attr('class','template_icon page_type_icon page_type_icon_sel');
	$j('#template').attr('value',val);
	
}
function NewPage_ActivateJCarousel(){
	if($j('#mycarousel').length>0)
	$j('#mycarousel').jcarousel({
		visible: 4
		,scroll: 1
		,start: 1
	});
}
function NewPage_ActivateSubJCarousel(){
	if($j('#subcarousel').length>0)
		$j('#subcarousel').jcarousel({
			visible: 4
			,scroll: 1
			,start: 1
		});
}
//========================== star rating system
/* AJAX Star Rating : v1.0.3 : 2008/05/06 */
/* http://www.nofunc.com/AJAX_Star_Rating/ */
function $O(v,o) { return((typeof(o)=='object'?o:document).getElementById(v)); }
function $S(o) { return((typeof(o)=='object'?o:$O(o)).style); }
function agent(v) { return(Math.max(navigator.userAgent.toLowerCase().indexOf(v),0)); }
function abPos(o) { var o=(typeof(o)=='object'?o:$O(o)), z={X:0,Y:0}; while(o!=null) { z.X+=o.offsetLeft; z.Y+=o.offsetTop; o=o.offsetParent; }; return(z); }
function XY(e,v) { var o=agent('msie')?{'X':event.clientX+document.documentElement.scrollLeft,'Y':event.clientY+document.documentElement.scrollTop}:{'X':e.pageX,'Y':e.pageY}; return(v?o[v]:o); }
star={};
star.mouse=function(e,o) { if(star.stop || isNaN(star.stop)) { star.stop=0;
    document.onmousemove=function(e) { var n=star.num;
        var p=abPos($O('star'+n)), x=XY(e), oX=x.X-p.X, oY=x.Y-p.Y; star.num=o.id.substr(4);
        if(oX<1 || oX>84 || oY<0 || oY>16) { star.stop=1; star.revert(); }
        else {
			nr = parseInt(oX/17) + 1;
			//if(oX <= 2) nr = '0';
			$O('starCur'+n).className = 'curr_rating vote_rating';
            $S('starCur'+n).width=nr*17+'px';
            $O('starCur'+n).title=nr;
            //$S('starUser'+n).color='#111';
            //$O('starUser'+n).innerHTML=Math.round(oX/74*100)+'%';
        }
    };
} };
star.update=function(e,o) { var n=star.num, v=parseInt($S('starCur'+n).width);
	//alert(current_photo);
    n=o.id.substr(4); //$O('starCur'+n).title=v;
    //$O('score'+n).value = v/20;
	//$O('starUser'+n).innerHTML = v/20;
	//alert(v/20);
	$j.post(HTTP + 'photos/vote_photo/'+current_photo+'/'+(v/17) + '/', 
	{}, function(response){
		if (response) {
			if(response == 'success'){
				$j('#photo_rating').load(HTTP + 'photos/load_rating/'+current_photo+'/',function(){
					$j('#right_photo_rating').html($j('#starUser').html());
				});
			}else alert(response);
		}
	});
    //req=new XMLHttpRequest(); req.open('GET',HTTP+'photos/vote_photo/'+current_photo+'/'+(v/20),false); req.send(null);
};
star.revert=function() { var n=star.num;// v=parseInt($O('starCur'+n).title);
	var x = parseFloat($O('starUser'+n).innerHTML);
	//alert(x);
	$S('starCur'+n).width=(x*17)+'px';
	$O('starCur'+n).className = 'curr_rating';
    //$S('starCur'+n).width=Math.round(x*74/100)+'px';
    //$O('starUser'+n).innerHTML=(v>0?Math.round(v)+'%':'');
    //$O('starUser'+n).style.color='#888';
    document.onmousemove='';
};
star.num=0;
function OrderSelectAlbumsBy(sel){
	if (sel!=''){
		$j('#div_gallery').html('<div align="center" style="padding-top: 100px;"><img src="'+ HTTP +'_layouts/images/loading.gif"></div>');
		$j('#div_gallery').load(HTTP + 'photos/ajax_select_albums/ajax/2/ord/' + sel);		
	}
}
function OrderSelectPhotosBy(sel,album){
	if (sel!=''){
		$j('#div_gallery').html('<div align="center" style="padding-top: 100px;"><img src="'+ HTTP +'_layouts/images/loading.gif"></div>');
		$j('#div_gallery').load(HTTP + 'photos/ajax_select_photo_gallery/'+album+'/ajax/1/ord/' + sel);		
	}
}
function Select_ComboAddedSelected(sel,album){
	if (sel != ''){
		adress = 'user/'+sel+'/'+order;
		$j('#div_gallery').html('<div align="center" style="padding-top: 100px;"><img src="'+ HTTP +'_layouts/images/loading.gif"></div>');
		$j.get(HTTP + 'photos/ajax_select_photo_gallery/'+album + '/ajax/1/sort/1/' + adress, {}, function(response){
			$j('#div_gallery').html(response);
		});
	}
}
function Select_DisplayUsedPhotos(usedphotos, album, index){
	$j('#div_gallery').html('<div align="center" style="padding-top: 100px;"><img src="'+ HTTP +'_layouts/images/loading.gif"></div>');
	if(usedphotos == 1){
		$j.get(HTTP + 'photos/ajax_select_photo_gallery/'+album + '/ajax/1/unused/1/', {}, function(response){
			$j('#div_gallery').html(response);
		});
	}else {
		$j.get(HTTP + 'photos/ajax_select_photo_gallery/'+album + '/ajax/1/unused/0/', {}, function(response){
			$j('#div_gallery').html(response);
		});
	}	
}
function Photos_ActivatePhotoClick(){
	$j('img.photo_details').each(function(){
		$j(this).unbind('click');
		$j(this).unbind('click').bind("click",function(){
			tb_remove();
		});
	});
}
function SelectProfilePhoto(id, index){
	$j.post(HTTP + 'photos/?insert_photo=' + index, 
	{id: id}, function (response) {
		if (response) {
			update = response.split('|||');
			PrepareResponse(update[0]);
			if(update[0] == 1){
				if(update[1] == 'success'){
					location.reload();
				}else if(update[1] == 'new'){
					page_modified = 1;
					$j('#but_add_photo').before(update[2]);
					nr_photos = $j('#now_photos').val();
					nr_photos++;
					max_photos = $j('#max_photos_total').val();
					if(nr_photos < max_photos){
					}else $j('#but_add_photo').hide();
					$j('#now_photos').val(nr_photos);
					is_cap = $j('#caption').val();
					if(is_cap != 1){
						$j('.link_caption').addClass('hidden');
					}
				}else if(update[1] == 'polls'){
					page_modified = 1;
					$j('#photo_item'+update[2]).html(update[3]);
				}else if(update[1] == 'montage'){
					page_modified = 1;
					idx = update[2];
					$j('#photo_src'+idx).remove();
					$j('#photo_item'+idx).prepend(update[3]);
					if($j('#photo_src_parent'+idx).length>0) $j('#photo_src_parent'+idx).remove();
					is_cap = $j('#caption'+idx).val();
					if(is_cap != 1){
						$j('#caption_add'+idx).attr('class','hidden');
						$j('#caption_div'+idx).attr('class','field_row hidden');
					}else{
						$j('#caption_add'+idx).attr('class','');
						$j('#caption_div'+idx).attr('class','field_row hidden');
						$j('#caption_'+idx).val('');
					}
				}else if(update[1] == 'author'){
					page_modified = 1;
					$j('#author_photoname').html(update[2]);
					$j('#but_author_photo').attr('value','Change...');
				}else{
					page_modified = 1;
					$j('#photo_src'+update[1]).remove();
					$j('#photo_item'+update[1]).prepend(update[2]);
				}
				tb_remove();
			}else alert(update[1]);
		}
	});
}
function Article_RemovePhoto(idx){
	$j.post(HTTP + 'pages/remove_article_photo/' + idx, 
	{}, function (response) {
		if (response) {
			update = response.split('|||');
			PrepareResponse(update[0]);
			if(update[0] == 1){
				page_modified = 1;
				nr_photos = $j('#now_photos').val();
				nr_photos--;
				max_photos = $j('#max_photos_total').val();
				$j('#now_photos').val(nr_photos);
				$j('#photo_item'+idx).remove();
				$j('#but_add_photo').show();
				tb_remove();
			}else alert(update[1]);
		}
	});
}
function Pages_DismissSuggestion(id){
	$j.post(HTTP + 'pages/dismiss_suggestion/' + id, 
	{}, function (response) {
		if (response) {
			update = response.split('|||');
			PrepareResponse(update[0]);
			if(update[0] == 1){
				location.reload();
				tb_remove();
			}else alert(update[1]);
		}
	});
}
function Pages_PollSelected(id,idx){
	if(id != ''){
		$j.post(HTTP + 'pages/page_poll_selected/' + id, 
		{}, function (response) {
			if (response) {
				update = response.split('|||');
				PrepareResponse(update[0]);
				if(update[0] == 1){
					$j('#award_winner_'+idx).html(update[1]);
					tb_remove();
				}else alert(update[1]);
			}
		});
	}else $j('#award_winner_'+idx).html('');
}

function HardCharacterLimit(field, maxL, counter){
	if(counter != '')
	obj_c = document.getElementById(counter);
	maxLen = maxL; // max number of characters allowed
	if (field.value.length > maxLen) {
		// Alert message if maximum limit is reached.
		// If required Alert can be removed.
		//var msg = "You have reached your maximum limit of characters allowed";
		//alert(msg);
		// Reached the Maximum length so trim the textarea
		field.value = field.value.substring(0, maxLen);
	}
	else  if(counter != ''){ // Maximum length not reached so update the value of my_text counter
		obj_c.innerHTML = maxLen - field.value.length;
	}
}
function ArticleTextLineCount(){
	var maxL = parseInt($j('#max_lines').val());
	var nr_photos = parseInt($j('#now_photos').val());
	var max_photos = parseInt($j('#max_photos').val());
	var lines_per_photo = parseInt($j('#lines_per_photo').val());
	var photos_diff = 0;
	if(nr_photos > max_photos) photos_diff = nr_photos - max_photos;
	
	limit = maxL - (photos_diff*lines_per_photo);
	PagesLineCount(document.getElementById('article_text'),limit,'ta_article_text');
}
function PagesLineCount(area,maxL,counter){
	var tw = $j(area).parent().children('div.twin');
	obj_c = document.getElementById(counter);
	var $textarea	=	jQuery(area);
	if(tw.length>0)
	var	$twin = tw;
	else{
		mimics2 = [
	   		'paddingTop',
	   		'paddingRight',
	   		'paddingBottom',
	   		'paddingLeft',
	   		'fontSize',
	   		'lineHeight',
	   		'fontFamily',
	   		'width',
	   		'fontWeight'];
		$twin		=	jQuery('<div class="twin" />').css({'position': 'absolute','display':'none','word-wrap':'break-word'});
		$twin.appendTo($textarea.parent());
		// Copy the essential styles (mimics) from the textarea to the twin
		var i = mimics2.length;
		while(i--){
			$twin.css(mimics2[i].toString(),$textarea.css(mimics2[i].toString()));
		}
	}
	var textareaContent = $textarea.val().replace(/&/g,'&amp;').replace(/  /g, '&nbsp;').replace(/<|>/g, '&gt;').replace(/\n/g, '<br />');
	if($twin.html() != textareaContent + '&nbsp;'){
		$twin.html(textareaContent+'&nbsp;');
	}
	xx = $twin.height();
	if($twin.html() == '&nbsp;') xx = 0;
	lines = parseInt(xx/16);
	obj_c.innerHTML = maxL - lines;
}
function Editor_EnableMember(id, pgid){
	$j.post(HTTP + 'editor/?enable_member=' + id + '&pgid=' + pgid, 
	{}, function (response) {		
		if(response == '1') $j('#img_display'+ id).html('<img src="'+HTTP+'_layouts/images/symbol_enabled.gif" width="14" alt="" border="0" />');
		else if(response == '0') $j('#img_display'+ id).html('<img src="'+HTTP+'_layouts/images/symbol_disabled.gif" width="14" alt="" border="0" />');
		else if(response) alert(response);
	})
}
// ============ script_ajax.js ========
var usertype = 'student';
var yearbook = '';
var maxpages = 0;
var pag = 0;
// variable to ignore the click after drag in firefox
var click_drag;
var IE = document.all ? true : false;
var downx=0;
var downy=0;
var upx=0;
var upy=0;
function GetMousePosUp(){
	// If NS -- that is, !IE -- then set up for mouse capture
	if (!IE) 
		document.captureEvents(Event.MOUSEUP);
	
	// Set-up to use getMouseXY function onMouseMove
	document.onmouseup = getMouseXYup;
	
	// Temporary variables to hold mouse x-y pos.s
	upx = 0;
	upy = 0;
	
}
// Main function to retrieve mouse x-y pos.s
function getMouseXYup(e) {
  if (IE) { // grab the x-y pos.s if browser is IE
    upx = event.clientX + document.body.scrollLeft;
    upy = event.clientY + document.body.scrollTop;
  } else {  // grab the x-y pos.s if browser is NS
    upx = e.pageX;
   	upy = e.pageY;
  }  
  // catch possible negative values in NS4
  if (upx < 0){upx = 0;}
  if (upy < 0){upy = 0;;}  
  // show the position values in the form named Show
  // in the text fields named MouseX and MouseY  
}
function GetMousePosDown(){
	// Detect if the browser is IE or not.
	// If it is not IE, we assume that the browser is NS.
	var IE = document.all ? true : false;
	
	// If NS -- that is, !IE -- then set up for mouse capture
	if (!IE) 
		document.captureEvents(Event.MOUSEDOWN);
	
	// Set-up to use getMouseXY function onMouseMove
	document.onmousedown = getMouseXYdown;
	
	// Temporary variables to hold mouse x-y pos.s
	downx = 0;
	downy = 0;
	
}
// Main function to retrieve mouse x-y pos.s
function getMouseXYdown(e) {
  if (IE) { // grab the x-y pos.s if browser is IE
    downx = event.clientX + document.body.scrollLeft;
    downy = event.clientY + document.body.scrollTop;
  } else {  // grab the x-y pos.s if browser is NS
    downx = e.pageX;
    downy = e.pageY;
  }  
  // catch possible negative values in NS4
  if (downx < 0){downx = 0;}
  if (downy < 0){downy = 0;}  
  // show the position values in the form named Show
  // in the text fields named MouseX and MouseY  
}
function IgnoreClick(){
	if ((Math.abs(downx - upx) <= 5) && (Math.abs(downy - upy) <= 5)) {
		//alert(Math.abs(downx - upx));
		return 1;
	}
	else {
		click_drag = 1;
		return 0;
	}
}
function SelectGroup(sel){
	$j('#div_selgroup').html('<img src="_layouts/images/loading.gif">');
	$j('#div_selgroup').load('index.php?select_group='+sel);
}

// ================== Editor functions
function DeleteQSet(id){
	
	$j.post(HTTP + 'index.php?delete_qset=' + id, 
	{}, function (response) {		
		if(response)
		if(response != 'The question set has been successfully deleted.') alert(response);	
		else location.reload();
	});
	
}
function DeletePoll(id){
	$j.post(HTTP + 'index.php?delete_poll=' + id, 
	{}, function (response) {		
		if(response)
		if(response != 'The poll has been successfully deleted.') alert(response);
		else document.location = HTTP + 'polls.html';
	})	
}
function DisplayHelp(sel){
	$j('#help').load(HTTP + 'index.php?show_help=' + sel);
}
function RestoreHelp(){
	$j('#help').load(HTTP + 'index.php?show_help=restore');
}
function ListSection(index, start, id){
	
	if (index != 0) {
	//	$j('#section_pages').html('<div align="center" style="padding-top: 100px;"><img src="_layouts/images/loading.gif"></div>');
		$j('#item_selected').load(HTTP + 'index.php?section_selected=' + index + '&start=' + start);
	//	$j('#section_pages').load(HTTP + 'index.php?list_section=' + index + '&start=' + start);
	}else{
		$j('#section_pages').html('');
		$j('#item_selected').load(HTTP + 'index.php?page_selected=' + id + '&start=' + start);
	}
}

function ListSelected(index, start){
	if(start == 0) start = '0';
	$j('#item_selected').load(HTTP + 'index.php?page_selected=' + index + '&start=' + start);
}
// ListTemplates - display the list of templates when a new type is selected
function ListTemplates(sel){
	$j('#template_det').html('');
	$j('#sele_template').html('<div align="center" style="width: 230px;"><img src="_layouts/images/loading.gif"></div>');
	$j('#sele_template').load(HTTP + 'index.php?list_templates=' + sel);
}
function AdminListTemplates(sel){
	$j('#sele_template').html('<div align="center" style="width: 230px;"><img src="_layouts/images/loading.gif"></div>');	
	$j('#sele_template').load(''+HTTP + 'admin.php?list_templates=' + sel+'');		
}

function AdminListTemplates_Edit(sel){
	$j('#sele_template').html('<div align="center" style="width: 230px;"><img src="_layouts/images/loading.gif"></div>');	
	$j('#sele_template').load(''+HTTP + 'admin.php?list_templates_edit=' + sel+'');		
}

function TemplateDetails(sel, type){
	// type = 2 - a profile template
	// type = 1 - other template
	$j('#template_det').html('<div align="center" style="padding-top: 45px;"><img src="_layouts/images/loading.gif"></div>');
	if(type == 1)
	$j('#template_det').load(HTTP + 'index.php?template_details=' + sel);
	else
	$j('#template_det').load(HTTP + 'index.php?template_details=' + sel +'&type=2');
}
function DeletePage(id){
	$j('#delete_message').html('');
	$j.post(HTTP + 'index.php?delete_page=' + id, 
	{}, function (response) {		
		if(response) 
			if(response != 'Page successfully deleted.')
				$j('#delete_message').html(response);
			else
				document.location = HTTP + 'index.php?page_manager';
	})
	//document.location = HTTP + 'index.php?page_manager';
}
function DeleteSection(id){
	$j.post(HTTP + 'index.php?delete_section=' + id, 
	{}, function (response) {		
		if(response)
			if(response != 'Section successfully deleted.')
				$j('#delete_message').html(response);
			else
				document.location = HTTP + 'index.php?page_manager';
		
	})
	//document.location = HTTP + 'index.php?page_manager';
}
function DeleteGroup(id){
	$j.post(HTTP + 'index.php?delete_group=' + id, 
	{}, function (response) {		
		if(response)
			if(response != 'The group has been successfully deleted.')
				alert(response);
			else
				location.reload();
		
	})	
}
function DeleteMember(id){
	$j.post(HTTP + 'editor/delete_member/' + id, 
	{}, function (response) {		
		if(response)
			if(response != 'The member has been successfully deleted.')
				alert(response);
			else{
				$j('#um_user_item'+id).remove();
			}
	});
}
function EdSelectPhoto(id, index){
	if (MONTAGE_PHOTO == 'select_user') {
		$j.post(HTTP + 'index.php?insert_user_photo=' + index, 
		{id: id}, function(response){
			if (response) {
				if (response != 'Photo successfully selected.') 
					alert(response);
				else {
					self.parent.tb_remove();
					self.parent.document.location = HTTP + 'edit_user_photos/0' + USERPROFILE_ID + '.html';
				}
			}
		})
	}else{
		$j.post(HTTP + 'index.php?insert_photo=' + index, 
		{id: id}, function (response) {
		if (response) {
			if (response != 'Photo successfully selected.') 
				alert(response);
			else {
				self.parent.tb_remove();
				self.parent.document.location = HTTP + 'user_photos/0' + USERPROFILE_ID + '.html';
			}
		}
	})
	}
	
	/*
	*/
}
// Select Photo for Montage Page
function EdSelectMPhoto(id, index){
	$j.post(HTTP + 'index.php?insert_montage_photo=' + index, 
	{id: id}, function (response) {
		if (response) {
			if (response != 'Photo successfully selected.') 
				alert(response);
			else {
				self.parent.tb_remove();
				self.parent.document.location = HTTP + 'edit_page/0' + PAGE_ID + '.html';
			}
		}
	})
	
}
function LockPage(id){
	sts = $j('#lock_link').html();	
	$j.post(HTTP + 'index.php?lock_page=' + id, 
	{ajaxlock: 1}, function (response) {
	if (response == 'ok') {
		if(sts == 'Lock Page'){
			$j('#lock_link').html('Unlock Page');
			$j('#lock_status').html('<span style="color: #FF0000; font-weight: bold;">Locked</span>');
		}else{
			$j('#lock_link').html('Lock Page');
			$j('#lock_status').html('Unlocked');
		}		
	}	
	})
}
function EnablePolls(){
	sts = $j('#polls_link').html();	
	$j.post(HTTP + 'index.php?enable_polls', 
	{}, function (response) {
	if (response == 'ok') {
		if(sts == 'Turn On'){
			$j('#polls_status').html('<span style="font-size: 13px; font-weight: bold; color: #008000;">On</span>');
			$j('#polls_link').html('Turn Off');
			
		}else{
			$j('#polls_status').html('<span style="font-size: 13px; font-weight: bold; color: #FF0000;">Off</span>');
			$j('#polls_link').html('Turn On');
			
		}
		
	}	
	})
}
function EnableComments(){
	sts = $j('#comments_link').html();
	
	$j.post(HTTP + 'index.php?enable_comments', 
	{}, function (response) {
	if (response == 'ok') {
		if(sts == 'Turn On'){
			$j('#comments_status').html('<span style="font-size: 13px; font-weight: bold; color: #008000;">On</span>');
			$j('#comments_link').html('Turn Off');
			
		}else{
			$j('#comments_status').html('<span style="font-size: 13px; font-weight: bold; color: #FF0000;">Off</span>');
			$j('#comments_link').html('Turn On');
			
		}
		
	}	
	})
}
function EdDeletePhoto(id){
	//alert('asdas');
	$j.post(HTTP + 'index.php?delete_photo=' + id, 
	{}, function (response) {
	if(response)
		if(response != 'The picture has been successfully deleted.')
			alert(response);	
	})
	var nr = parseInt($j('#selected_photos').html());
	clasa = $j('#photo_item' + id).attr('class');
	if (clasa.indexOf('ed_photo_item_over2') >= 0) {
		nr--;
		$j('#photo_item'+id).removeClass('ed_photo_item_over2');
	}
	if(nr == 0) nr = '0';
	$j('#selected_photos').html(nr);

	$j('#all_gallery').html('<div align="center" style="padding-top: 100px;"><img src="_layouts/images/loading.gif"></div>');
	$j('#all_gallery').load(HTTP + 'index.php?photo_gallery=-5&ajax=1&sort=1' + adress + '&pag=' + pag);
}
// ================= User functions
// delete photo
function DeletePhoto(id){
	$j.post(HTTP + 'index.php?delete_photo=' + id, 
	{}, function (response) {
	if(response)
		if(response != 'The picture has been successfully deleted.')
			alert(response);
	})
	$j('#all_gallery').html('<div align="center" style="padding-top: 100px;"><img src="_layouts/images/loading.gif"></div>');
	$j('#all_gallery').load(HTTP + 'index.php?photo_gallery=-1&ajax=1&sort=1' + adress + '&pag=' + pag);
}
function SelectPhoto(id, index){
	$j.post(HTTP + 'index.php?insert_photo=' + index, 
	{id: id}, function (response) {
		if (response) {
			if (response != 'Photo successfully selected.') 
				alert(response);
			else {
				self.parent.tb_remove();
				self.parent.document.location = HTTP + 'my_profile_page/03.html';
			}
		}
	})	
}
function MakePhotoMandatory(index, check){
	$j.post(HTTP + 'index.php?make_photo=' + index, 
	{make: check}, function (response) {
	 if(response) alert(response);
	})
}
function ShowStylePhoto(crt){
	$j.post(HTTP + 'index.php?show_style_photo=' + crt, 
	{}, function (response) {
	 if(response) $j('#current_pic').html(response);
	})
}
function GoToPage(page,address,maxpage){
	if(page < 0) page = 1;
	if(page > maxpage) page = maxpage;
	//alert(HTTP + address + '/pag/' + page);	
	pag = page;
	$j('#div_gallery').html('<div align="center" style="padding-top: 100px;"><img src="'+ HTTP +'_layouts/images/loading.gif"></div>');
	$j.get(HTTP + address + '/pag/' + page, {}, function(response) {
		$j('#div_gallery').html(response);
		SetSWFAddress('pag',page);
	});	
}
function GoToPageClassic(page,address,maxpage){
	if(page < 0) page = 1;
	if(page > maxpage) page = maxpage;
	pag = page;
	$j('#div_gallery').html('<div align="center" style="padding-top: 100px;"><img src="'+ HTTP +'_layouts/images/loading.gif"></div>');
	$j.get(HTTP + address + '&pag=' + page, {}, function(response) {
		$j('#div_gallery').html(response);		
	});	
}
function GetSWFAddress(address){	
	//alert(SWFAddress.getValue());
	var adr = SWFAddress.getValue();
	//alert(HTTP + address + adr);
	if(adr != '/'){
		//alert('mere');
		//alert(HTTP + address + adr);
		$j.get(HTTP + address + adr, {}, function(response) {
			$j('#div_gallery').html(response);		
		});
	}
}

function SetSWFAddress(item,value){
	var adr = SWFAddress.getValue();
	if(adr != '/'){		
		var vars = adr.split('/');
		var count;
		var count1;
		var flag=0;
		var flag1=0;
		
		if(item =='ord'){
			for (count = 0; count < vars.length; count++){
				if(vars[count] == 'pag'){
					count1 = count+1;
					vars[count1] = 1;
					flag1=1;
				}else if(vars[count] == 'user'){
					count1 = count+1;
					vars[count1] = 'all';
					flag1=1;
				}else if(vars[count] == 'ord'){
					count1 = count+1;
					vars[count1] = value;
					flag=1;	
				}
			}
		}else if(item =='user'){
			for (count = 0; count < vars.length; count++){
				if(vars[count] == 'pag'){
					count1 = count+1;
					vars[count1] = 1;
					flag1=1;
				}else if(vars[count] == 'ord'){
					count1 = count+1;
					vars[count1] = 1;
					flag1=1;
				}else if(vars[count] == 'user'){
					count1 = count+1;
					vars[count1] = value;
					flag=1;	
				}
			}
		}else if(item =='pag'){
			for (count = 0; count < vars.length; count++){
				if(vars[count] == 'pag'){
					count1 = count+1;
					vars[count1] = value;
					flag=1;	
				}
			}
		}		
		if(flag == 1){
			var new_adr = vars.join('/');
			SWFAddress.setValue(new_adr);
		}else if(flag1==1){
			var new_adr = vars.join('/');
			SWFAddress.setValue(new_adr+'/'+item+'/'+value);
		}else SWFAddress.setValue(adr+'/'+item+'/'+value);
	}else SWFAddress.setValue(item+'/'+value);
}
var adress = '';
var order = '';
function ComboAddedSelected(sel,album){
	if (sel != ''){
		adress = 'user/'+sel+'/'+order;
		$j('#div_gallery').html('<div align="center" style="padding-top: 100px;"><img src="'+ HTTP +'_layouts/images/loading.gif"></div>');
		$j.get(HTTP + 'photos/ajax_photo_gallery/'+album + '/ajax/1/sort/1/' + adress, {}, function(response){
			$j('#div_gallery').html(response);
			SetSWFAddress('user',sel);
		});
	}
}
function ComboUserSelected(sel, index){
	if (sel != '') {
		if (sel == 'all_users') 
			adress = adress + '&user=all';
		else 
			adress = adress + '&user=' + sel;
		$j('#all_gallery').html('<div align="center" style="padding-top: 100px;"><img src="_layouts/images/loading.gif"></div>');
		if (index == -1) {
			$j('#all_gallery').load(HTTP + 'index.php?photo_gallery=' + index + '&ajax=1&sort=1' + adress);
		}
		else if(index == -5){
			$j('#all_gallery').load(HTTP + 'index.php?photo_gallery=' + index + '&ajax=1&sort=1' + adress);
		}
		else if(index == -3){
			//$j('#admins').html('adafakfhjshgksgfg');
			//$j('#admins').load(HTTP + 'index.php?subeditor_admins=' + sel);
		}
		else {
			if(MONTAGE_PHOTO == 'montage')
			$j('#all_gallery').load(HTTP + 'index.php?montage_photo=' + index + '&ajax=1&sort=1' + adress);
			else if(MONTAGE_PHOTO == 'select_user')
			$j('#all_gallery').load(HTTP + 'index.php?select_user_photo=' + index + '&ajax=1&sort=1' + adress);
			else
			$j('#all_gallery').load(HTTP + 'index.php?select_photo=' + index + '&ajax=1&sort=1' + adress);
		}
	}else if(index == -3){
		alert('Please select a person!');
	}
}
var selected = '';
function OrderBy(sel, index){
	if (sel!=''){
		selected = sel;		
		order = '/ord/' + sel;
		$j('#div_gallery').html('<div align="center" style="padding-top: 100px;"><img src="'+ HTTP +'_layouts/images/loading.gif"></div>');
		
		if (index == -1) {
			$j('#div_gallery').load(HTTP + 'photos/ajax_photo_gallery/' + index + '/ajax/sort/1' + order);
		}else if(index == -5){
			$j('#div_gallery').load(HTTP + 'photos/ajax_photo_gallery/' + index + '/ajax/sort/1' + order);
		}
		else {			
			if(MONTAGE_PHOTO == 'montage')
			$j('#all_gallery').load(HTTP + 'index.php?montage_photo=' + index + '&ajax=1&sort=1' + adress);
			else if(MONTAGE_PHOTO == 'select_user')
			$j('#all_gallery').load(HTTP + 'index.php?select_user_photo=' + index + '&ajax=1&sort=1' + adress);
			else
			$j('#all_gallery').load(HTTP + 'index.php?select_photo=' + index + '&ajax=1&sort=1' + adress);
		}
	}
}
function DisplayUsedPhotos(usedphotos, index){
	
	$j('#all_gallery').html('<div align="center" style="padding-top: 100px;"><img src="_layouts/images/loading.gif"></div>');
	if(usedphotos == 1){
		adress = adress + '&unused=1';
		
	}else {
		adress = adress + '&unused=0';
	}	
	
	if(MONTAGE_PHOTO == 'montage')
		$j('#all_gallery').load(HTTP + 'index.php?montage_photo=' + index + '&ajax=1&sort=1' + adress);
	else if(MONTAGE_PHOTO == 'select_user')
		$j('#all_gallery').load(HTTP + 'index.php?select_user_photo=' + index + '&ajax=1&sort=1' + adress);
	else{
		
		$j('#all_gallery').load(HTTP + 'index.php?select_photo=' + index + '&ajax=1&sort=1' + adress);
	}
		
}
function votePhoto(id,rate){
	$j('#picture_' + id).load('index.php?vote=' + id + '&rate=' + rate);
}
function voteDetPhoto(id,rate){	
	$j('#picdetails2').load(HTTP + 'index.php?vote_details=' + id + '&rate=' + rate);
}
function VotePoll(id){
	$j('div.poll_voted_').html('');
	ob = fieldOb('combo_sel_'+id);
	if(ob.value == '') return;	
	$j.post(HTTP + 'polls/vote_poll/' + id,
	{choice: ob.value}, function (response) {
		if(response && response == 'Success!'){
			window.location.reload();
			$j('#butvoteclown_' + id).attr('value', 'Change Vote');
			$j('#poll_voted' + id).html('Vote cast!');
			$j('#poll_results' + id).load(HTTP+'polls/polls_top/' + id);
		}
	})
}
function UsePollChoices(sel){
	
	$j('form#formPoll input[@type=radio]').each(function(){
		if(this.value == sel)
			this.checked = true;
		else
			this.checked = false;
	});
}
function ImportCsv(sel){	
	$j('form#formAddMembers input[@type=radio]').each(function(){
		if(this.value == sel)
			this.checked = true;
		else
			this.checked = false;
	});
}
function AdminTotalChars(sel){
	$j('form#formTemplates input.totalchs').each(function(){
		if(this.value == sel)
			this.checked = true;
		else
			this.checked = false;
	});
}
function FinishCategory(sel){
	$j('#to_do_list').html('<div align="center" style="padding-top: 100px;"><img src="_layouts/images/loading.gif"></div>');
	$j('#to_do_list').load(HTTP + 'index.php?finish_category=' + sel);
/*	$j.post(HTTP + 'index.php?finish_category=' + sel, 
		{}, function (response) {
			
		})*/
}
function MoveToSection(sel, thepage){
	$j.post(HTTP + 'index.php?move_to_category=' + sel, 
		{pageid: thepage}, function (response) {
			if (response) 
				if (response != 'success') 
					alert(response);
				else {
					if(sel != 0)
					document.location = 'index.php?page_manager&section=' + sel +'&selected_page=' + thepage;
					else
					document.location = 'index.php?page_manager&section=' + sel +'&page=' + thepage;
				}
		});
}
function SelectFacebookDiv(pid){
	ob = fieldOb('select_'+pid);
	if (ob.checked) {
		SelectFacebookPhoto(pid, 0);
		ob.checked = false;
		$j('#photo_item'+pid).removeClass('ed_photo_item_over2');
	}else{
		SelectFacebookPhoto(pid, 1);
		$j('#photo_item'+pid).addClass('ed_photo_item_over2');
		ob.checked = true;
	}
}
function SelectFacebookPhoto(pid, mode){
	//alert(pid);
	ob = fieldOb('select_'+pid);
	nr_pics = parseInt($j('#nr_sel_pics').html());
	
	if (mode == 1) {
		nr_pics = nr_pics + 1;
	}
	else {
		nr_pics = nr_pics - 1;
	}
	if(nr_pics == 0 || nr_pics < 0)
		nr_pics = '0';
	$j('#nr_sel_pics').html(nr_pics);
	$j.post(HTTP + 'photos/?select_facebook_photo=' + pid, 
		{mode: mode}, function (response) {
			if (response)
				alert(response);
		});
}
function PhotoClicked(id){	
	clasa = $j('#but_batch').attr('class');	
	if(clasa == 'inputButton120_over'){
		var nr = parseInt($j('#selected_photos').html());
		if(nr>19) alert('You can select maxim 20 photos');
		else{ 
			$j.post(HTTP + 'photos/photo_clicked/' + id,
				{}, function (response) {
				if (response) 
					if (response == 'selected'){
						$j('#photo_item'+id).addClass('ed_photo_item_over2');
						nr++;
						if(nr == 0) nr = '0';
						$j('#selected_photos').html(nr);
					}else if (response == 'unselected'){
						$j('#photo_item'+id).removeClass('ed_photo_item_over2');
						nr--;
						if(nr == 0) nr = '0';
						$j('#selected_photos').html(nr);
					}else alert(response);
			});
		}
	}else{
		document.location=HTTP+'photos/view_photo/'+id;
	}
}
function SelectAllPhotos(){
	ob = fieldOb('photo_ids');
	
	//var ids = $j('#photo_ids').value;
	//alert(ob.value);
	ids = ob.value.split(',');
	//alert(ids.length);
	var nr = parseInt($j('#selected_photos').html());
	for (i = 0; i < ids.length; i++) {
		clasa = $j('#photo_item' + ids[i]).attr('class');
		if (clasa.indexOf('ed_photo_item_over2') < 0) {
			nr++;
			if(nr<20)
				$j('#photo_item'+ids[i]).addClass('ed_photo_item_over2');
			else{ 
				alert('You can select maxim 20 photos'); break;}
		}
	}
	if(nr == 0) nr = '0';
	$j('#selected_photos').html(nr);	
	$j.post(HTTP + 'photos/photo_clicked_all/' + ob.value, {}, function (response) {});
	
}
function SelectNoPhoto(){
	ob = fieldOb('photo_ids');	
	ids = ob.value.split(',');	
	var nr = parseInt($j('#selected_photos').html());	
	for (i = 0; i < ids.length; i++) {
		clasa = $j('#photo_item' + ids[i]).attr('class');
		if (clasa && clasa.indexOf('ed_photo_item_over2') >= 0) {
			nr--;
			$j('#photo_item'+ids[i]).removeClass('ed_photo_item_over2');
		}
	}
	if(nr == 0) nr = '0';
	$j('#selected_photos').html(nr);
	$j.post(HTTP + 'photos/photo_clicked_none/' + ob.value, 
		{}, function (response) {

		});
	
}
function ClearSelection(address){
	ob = fieldOb('photo_total_ids');	
	ids = ob.value.split(',');	
	var nr = parseInt($j('#selected_photos').html());	
	for (i = 0; i < ids.length; i++) {
		clasa = $j('#photo_item' + ids[i]).attr('class');
		if (clasa && clasa.indexOf('ed_photo_item_over2') >= 0) {
			nr--;
			$j('#photo_item'+ids[i]).removeClass('ed_photo_item_over2');
		}
	}
	if(nr == 0) nr = '0';
	$j('#selected_photos').html(nr);
	$j.post(HTTP + 'photos/photo_clicked_none/' + ob.value, 
		{}, function (response) {

		});
//	//alert(address);
//	$j('#selected_photos').html('0');
//	$j.post(HTTP + 'photos/photo_clicked_clear/', 
//		{}, function (response) {
//
//		});
//
//	window.location=HTTP + address;
	
//	$j('#div_gallery').html('<div align="center" style="padding-top: 100px;"><img src="'+ HTTP +'_layouts/images/loading.gif"></div>');
//	
//	$j.get(HTTP + address, {}, function(response) {
//		$j('#div_gallery').html(response);		
//	});
	
}

// admin jscript ================
function SetAddPhotos(){
	ob = fieldOb('add_pics');
	if (ob.value != '' && ob.value != 0) {
		$j('#div_set_photos').html('<div align="center" style="width: 250px;"><img src="_layouts/images/loading.gif" /></div>');
		$j('#div_set_photos').load(HTTP + 'admin.php?show_add_fields=' + ob.value);
		
	}else {
		alert('Enter the amount of additional pictures!');
	}
}
function HideComboTemplate(type){
	div = eval("document.getElementById('combo_template')");	
		if(type ==  'photo') div.className = 'hidden';
		if(type ==  'special') div.className = 'visibile';
		if(type ==  'profile') div.className = 'hidden';
}
function HideContentSubtypeTemplate(type){
	div_custom = eval("document.getElementById('content_custom')");
	div_polls = eval("document.getElementById('content_polls')");
	div_photo = eval("document.getElementById('content_photo')");
	div_profile = eval("document.getElementById('content_profile')");
	
	div_custom.className = 'hidden';
	div_polls.className = 'hidden';
	div_photo.className = 'hidden';
	div_profile.className = 'hidden';
	
	$j('#content_'+type).removeClass('hidden');
}
function RotatePhoto(){	
	$j.post(HTTP + 'photos/rotate_photo/' + page, {}, function(response) {
		$j('#div_gallery').html(response);		
	});
	$j('#div_gallery').html('<div align="center" style="padding-top: 100px;"><img src="'+ HTTP +'_layouts/images/loading.gif"></div>');
	$j.get(HTTP + address + '/pag/' + page, {}, function(response) {
		$j('#div_gallery').html(response);
	});
}
var selected = '';
function OrderAlbumsBy(sel){
	if (sel!=''){
		$j('#div_gallery').html('<div align="center" style="padding-top: 100px;"><img src="'+ HTTP +'_layouts/images/loading.gif"></div>');
		$j('#div_gallery').load(HTTP + 'photos/ajax_albums/ajax/1/ord/' + sel);
		SetSWFAddress('ord',sel);	
	}
}
function OrderPhotosBy(sel,album){
	if (sel!=''){		
		$j('#div_gallery').html('<div align="center" style="padding-top: 100px;"><img src="'+ HTTP +'_layouts/images/loading.gif"></div>');
		$j('#div_gallery').load(HTTP + 'photos/ajax_photo_gallery/'+album+'/ajax/1/ord/' + sel);
		SetSWFAddress('ord',sel);		
	}
}
function TimeOut(func){	
	 t = setTimeout(""+func+"", 100);		
}
function ChangePhoto(photo,album){
	if (photo!=''){
		$j('#album_photo').html('<div align="center" style="padding-top: 100px;"><img src="'+ HTTP +'_layouts/images/loading.gif"/></div>');
		$j('#album_photo').html('<img src="'+ HTTP +'upload/Yearbook_'+album+'/photos_small/'+photo+'"/>');
	}
}
function ButBatch(){
	clasa = $j('#but_batch').attr('class');	
	if(clasa == 'inputButton120_over'){
		ClearSelection();
		$j('#div_batch_photos').hide();
		$j('#but_batch').removeClass('inputButton120_over'); 
		$j('#but_batch').addClass('inputButton120');
		$j('#batch_text').removeClass(''); 
		$j('#batch_text').addClass('ascuns');
		$j('#batch_buttons').removeClass(''); 
		$j('#batch_buttons').addClass('ascuns');
	}else{		
		$j('#div_batch_photos').show();
		$j('#but_batch').removeClass('inputButton120'); 
		$j('#but_batch').addClass('inputButton120_over');
		$j('#batch_text').removeClass('ascuns'); 
		$j('#batch_text').addClass('');
		$j('#batch_buttons').removeClass('ascuns'); 
		$j('#batch_buttons').addClass('');
	}
}
function ButUpload(type){
	$j('#div_add_simple').addClass('ascuns');
	$j('#div_add_multiple').addClass('ascuns');
	$j('#div_add_facebook').addClass('ascuns');
	$j('#title_add1').addClass('ascuns');
	$j('#title_add2').addClass('ascuns');
	$j('#title_add3').addClass('ascuns');
	
	if(type==3){
		$j('#but_add1').removeClass('inputButton100_over'); 
		$j('#but_add1').addClass('inputButton100');
		$j('#but_add2').removeClass('inputButton120_over'); 
		$j('#but_add2').addClass('inputButton120');
		$j('#but_add3').removeClass('inputButton120'); 
		$j('#but_add3').addClass('inputButton120_over');
		
		$j('#div_add_facebook').removeClass('ascuns'); 
		$j('#div_add_facebook').addClass('');
		
		$j('#title_add3').removeClass('ascuns'); 
		$j('#title_add3').addClass('');
		
	}else if(type==2){
		$j('#but_add1').removeClass('inputButton100_over'); 
		$j('#but_add1').addClass('inputButton100');
		
		$j('#but_add2').removeClass('inputButton120'); 
		$j('#but_add2').addClass('inputButton120_over');
		
		$j('#but_add3').removeClass('inputButton120_over'); 
		$j('#but_add3').addClass('inputButton120');
		
		$j('#div_add_multiple').removeClass('ascuns'); 
		$j('#div_add_multiple').addClass('');
		
		$j('#title_add2').removeClass('ascuns'); 
		$j('#title_add2').addClass('');
		
	}else{
		$j('#but_add1').removeClass('inputButton100'); 
		$j('#but_add1').addClass('inputButton100_over');
		$j('#but_add2').removeClass('inputButton120_over'); 
		$j('#but_add2').addClass('inputButton120');
		$j('#but_add3').removeClass('inputButton120_over'); 
		$j('#but_add3').addClass('inputButton120');
		
		$j('#div_add_simple').removeClass('ascuns'); 
		$j('#div_add_simple').addClass('');
		
		$j('#title_add1').removeClass('ascuns'); 
		$j('#title_add1').addClass('');
	}
}
function CheckEditPhotos(frm){
	//alert(document.frmRotate.rotate.value);
	if(document.frmRotate.rotate.value == 6){
		if(window.confirm('Are you sure you want to delete this photo? This action cannot be undone!')) 
			if(window.confirm('ARE YOU SURE?')){
				return true;}
			else{
			return false;
			}
		else return false;
	}
	if(document.frmRotate.rotate.value == 5){
		tb_show('Select Album',HTTP+'photos/?confirm_move_photos&height=90&width=200',false);
		return false;
	}	
	if(document.frmRotate.rotate.value == 7){
		tb_show('Select Album',HTTP+'photos/?confirm_assign_photos&height=90&width=200',false);
		return false;
	}	
}
function CheckMovePhotos(){
	//alert(document.frmMove.album.value);
	var album = document.frmMove.album.value;	
	if(album){
		document.location=HTTP+'photos/move_photos/'+album;
	}
	return false;
	tb_remove();
}
function CheckAssignPhotos(){
	//alert(document.frmMove.to_user.value);
	var album = document.frmMove.to_user.value;	
	if(album){
		document.location=HTTP+'photos/assign_photos/'+album;
	}
	return false;
	tb_remove();
}
function PostComment(photo){	
	//alert(photo);
	var comment = document.frmComment.comment.value;	
	 $j.post(HTTP+'photos/post_comment/' + photo, {step: 2,comment: comment}, function(response){
		if(response == 'Please write a comment!')
			alert('Please write a comment!');
		else{
			$j.get(HTTP+'photos/load_comment/' + response, {}, function(resp){				
				if($j('#list_comments').length && $j('#list_comments').html() == 'No comments...') $j('#list_comments').html('');
				$j('#div_comments').append(resp);
				$j('#comment').attr('value', 'Write a comment...');				
				
			 });
		} 
	 });
	return false;
}
function CheckBoxEdit(id){
	if(id==5) $j('#name_photo').attr('class', '');
	else $j('#name_photo').attr('class', 'ascuns');	
}
function CheckEditPhoto(){
	alert(document.frmRotate.rotate.value);
	if(document.frmRotate.rotate.value == 6){
		if(window.confirm('Are you sure you want to delete this photo? This action cannot be undone!')) 
			if(window.confirm('ARE YOU SURE?')){
				return true;}
			else{
			return false;
			}
		else return false;
	}
	if(document.frmRotate.rotate.value == 5){
		tb_show('Select Album',HTTP+'photos/?confirm_move_photos&height=90&width=200',false);
		return false;
	}	
}
function DetailsPhoto(){
	if ($j('img.photo_details').length > 0)
		$j('img.photo_details').cluetip({
			tracking:true
			,width:150
			,positionBy:'mouse'
			,dropShadow:false
			,attribute:'alt'
			,cluetipClass: 'jtip'
		});
}
function GoToPhoto(photo){
	document.location=HTTP + 'photos/view_photo/' + photo;
}
function drawGraph(id,val1,val2,val3,val4,val5,val6,options) {
    var layout = new PlotKit.Layout("pie", options);
    layout.addDataset("sqrt", [[0, 0], val1, val2, val3, val4, val5, val6]);
    layout.evaluate();
    var canvas = MochiKit.DOM.getElement("graph_"+id);
    var plotter = new PlotKit.SweetCanvasRenderer(canvas, layout, options);
    plotter.render();
}
function TemplateStyles(value){
	  $j.post('?show_styles='+value, {}, function(response){
		  $j("#div_styles").html(response);
		});	
	  $j.post('?show_book_type=0', {}, function(response){
		  $j("#div_book_type").html(response);
		});	  
}
function TemplateBookType(value){
	if(value>0){
	  $j.post('?show_book_type='+value, {}, function(response){
		  $j("#div_book_type").html(response);
		});	
	}
}
function ShowTemplateType(value){
	if(value==1){
		$j('#template_type').removeClass('ascuns'); 
		$j('#template_type').addClass('field_row');
	}else {
		$j('#template_type').removeClass('field_row'); 
		$j('#template_type').addClass('ascuns');
	} 
}
function TemplateType(value){
  $j.post('?show_template_type_'+value, {}, function(response){
	  $j("#div_template_type").html(response);
	});
}
var nr_caption = 0 ;
if ($j("#nr_caption").length > 0)
var nr_caption = $j('#nr_caption').val();
function ShowCaption(id,val){
	if(val==1){
		nr_caption++;
		$j('#div_caption').removeClass('ascuns');		
		$j('#div_caption').addClass('field_row');
		
		$j('#div_caption_'+id).removeClass('ascuns'); 
		$j('#div_caption_'+id).addClass('view');		
	}else{
		nr_caption--;
		$j('#div_caption_'+id).removeClass('view'); 
		$j('#div_caption_'+id).addClass('ascuns');
		if(nr_caption==0){
			$j('#div_caption').removeClass('field_row'); 
			$j('#div_caption').addClass('ascuns');
		}
	} 
}
function TemplateAddTextfield11(id){
	var val = $j('#nr_textfield').val();
	if(val<6){		
		$j.get('?show_template_textfield='+val, {id:id}, function(response){
			$j("#div_textfield").html(response);
		});
	}else alert("You can add a maximum of 5 Textfield");
}
function TemplateAddTextarea111(id){
	var val = $j('#nr_textarea').val();
	if(val<4){		
		$j.get('?show_template_textarea='+val, {id:id}, function(response){
			$j("#div_textarea").html(response);
		});
	}else alert("You can add a maximum of 3 Textarea");
}
function TemplateAddPhotos(id){
	var val = $j('#nr_pictures').val();
	if(val<4){		
		$j.get('?show_template_photos='+val, {id:id}, function(response){
			$j("#div_pictures").html(response);
		});
		
	}
}
function ShowLineCounting(val){
	if(val==1){
		$j('#div_count_total').removeClass('ascuns'); 
		$j('#div_count_total').addClass('');
		$j('#div_count_user').removeClass(''); 
		$j('#div_count_user').addClass('ascuns');
		$j('#div_count_friends').removeClass(''); 
		$j('#div_count_friends').addClass('ascuns');
	}else{
		$j('#div_count_total').removeClass(''); 
		$j('#div_count_total').addClass('ascuns');
		$j('#div_count_user').removeClass('ascuns'); 
		$j('#div_count_user').addClass('');
		$j('#div_count_friends').removeClass('ascuns'); 
		$j('#div_count_friends').addClass('');
	}	
}
function ShowLinkAddPict(){
	$j('#link_add_pict').removeClass('ascuns'); 
	$j('#link_add_pict').addClass('');
}
function ShowLink(value){
	$j('#link_'+value).removeClass('ascuns'); 
	$j('#link_'+value).addClass('');
}
//profile
function TemplateProfileAddPictures(){
	var pict = $j('#nr_pictures').val();
	var pict1 = $j('#nr_pictures1').val();
	var id_div = parseInt(pict)+1;
	var id_div1 = parseInt(pict1)+1;
	$j('#nr_pictures').val(id_div);
	$j('#nr_pictures1').val(id_div1);	
	$j.post('?show_template_add_picture',{id_div:id_div1,nr_div:id_div},function(response){
		//alert(id_div1);
		//alert(id_div);
		$j('#div_pictures').append(response);
	});
}
function DeletePicture(val){
	$j('#delete_picture_'+val).attr('checked', true);
	$j('#picture_'+val).html('');
	var pict = $j('#nr_pictures').val();
	var pict1 = $j('#nr_pictures1').val();
	pict = parseInt(pict);
	pict1 = parseInt(pict1);
	//alert('pict: '+pict);
	var x=1;	
	for(i=1;i<=pict1;i++){
		//alert('i: '+i);
		if($j('#delete_picture_'+i).val() != 1){
			//alert('da');
		}else{
			//alert('nu');
			$j('#nr_pict_'+i).html(x);
			x++;
		}
	}
	var y=pict-1;
	$j('#nr_pictures').val(y);
}
function TemplateCheckProfile(){
	var value = $j('#profiles').val();
	if(value == 0.5 || value == 1 || value == 2 || value == 3 || value == 4 || value == 5 || value == 6 || value == 7 || value == 8 || value == 9 || value == 10 || value == 11 || value == 12 || value == 13 || value == 14 || value == 15 || value == 16 || value == 17 || value == 18 || value == 19 || value == 20){		
		var x=1;
	}else{
		alert('Error: Number of profile per page must be 0.5 or contained between 1 and 20'); 
		$j('#profiles').val('');
	}
}
function TemplateAddLine(id){
	var l_name = $j('#line_name').val();
	var l_limit = $j('#line_limit').val();
	var c_about = 0;
	var c_questions = 0;
	var c_say = 0;
	var c_comments = 0;
	var c_details = 0;
	if(l_name == ''){
		alert('Please select the name');
		return false;
	}
	if(l_limit == ''){
		alert('Please select the limit');
		return false;
	}
	if($j('#count_about').attr('checked')){
		c_about = 1;
		$j('#line_about').removeClass('field_row'); 
		$j('#line_about').addClass('ascuns');
	}
	if($j('#count_questions').attr('checked')){
		c_questions = 1;
		$j('#line_questions').removeClass('field_row'); 
		$j('#line_questions').addClass('ascuns');
	}
	if($j('#count_say').attr('checked')){
		c_say = 1;
		$j('#line_say').removeClass('field_row'); 
		$j('#line_say').addClass('ascuns');
	}
	if($j('#count_comments').attr('checked')){
		c_comments = 1;
		$j('#line_comments').removeClass('field_row'); 
		$j('#line_comments').addClass('ascuns');
	}
	if($j('#count_details').attr('checked')){
		c_details = 1;
		$j('#line_details').removeClass('field_row'); 
		$j('#line_details').addClass('ascuns');
	}
	
	if(c_about == 0 && c_questions == 0 && c_say == 0 && c_comments == 0 && c_details == 0){
		alert('Please select at least one component');
		return false;
	}
	var lines = $j('#nr_lines').val();
	$j.post('?show_template_add_line',{template_id:id,name:l_name,limit:l_limit,about:c_about,questions:c_questions,say:c_say,comments:c_comments,details:c_details},function(response){		
		if(lines==0) $j('#div_counting').html(response);
		else $j('#div_counting').append(response);
		lines++;
		$j('#nr_lines').val(lines);
		$j('#count_about').attr('checked',false);
		$j('#count_questions').attr('checked',false);
		$j('#count_say').attr('checked',false);
		$j('#count_comments').attr('checked',false);
		$j('#count_details').attr('checked',false);
		$j('#line_name').val('');
		$j('#line_limit').val('');
	});
}
function DeleteLine(id){
	$j.post('?show_template_delete_line='+id,{},function(response){
		//alert(response);
		if(response!='error'){
			$j('#line_'+id).addClass('ascuns');
			$j('#line_name').val('');
			$j('#line_limit').val('');
			var lines = $j('#nr_lines').val();
			lines--;
			$j('#nr_lines').val(lines);
			if(lines==0) $j('#div_counting').html('<span style="font-style: italic">Add line counts below</span>');
			var str = response;
			if(str.substr(0,1) == 1){				
				$j('#line_about').removeClass('ascuns'); 
				$j('#line_about').addClass('field_row');
			}
			if(str.substr(1,1) == 1){
				$j('#line_questions').removeClass('ascuns'); 
				$j('#line_questions').addClass('field_row');
			} 
			if(str.substr(2,1) == 1){
				$j('#line_say').removeClass('ascuns'); 
				$j('#line_say').addClass('field_row');
			} 
			if(str.substr(3,1) == 1){
				$j('#line_comments').removeClass('ascuns'); 
				$j('#line_comments').addClass('field_row');
			} 
			if(str.substr(4,1) == 1){
				$j('#line_details').removeClass('ascuns'); 
				$j('#line_details').addClass('field_row');
			} 
		}
	});
}
function CheckLineCounting(){	
	if($j('#about_me').attr('checked')){
		$j('#line_about').removeClass('ascuns'); 
		$j('#line_about').addClass('field_row');	
	}else{
		$j('#line_about').removeClass('field_row'); 
		$j('#line_about').addClass('ascuns');
	}
	
	if($j('#questions').attr('checked')){
		$j('#line_questions').removeClass('ascuns'); 
		$j('#line_questions').addClass('field_row');	
	}else{
		$j('#line_questions').removeClass('field_row'); 
		$j('#line_questions').addClass('ascuns');
	}
	if($j('#friends_say').attr('checked')){
		$j('#line_say').removeClass('ascuns'); 
		$j('#line_say').addClass('field_row');	
	}else{
		$j('#line_say').removeClass('field_row'); 
		$j('#line_say').addClass('ascuns');
	}
	if($j('#friends_comments').attr('checked')){
		$j('#line_comments').removeClass('ascuns'); 
		$j('#line_comments').addClass('field_row');	
	}else{
		$j('#line_comments').removeClass('field_row'); 
		$j('#line_comments').addClass('ascuns');
	}
}
function TemplateProfileAddPictures1(value){
	var pict = $j('#nr_pictures').val();
	$j.post('?show_template_add_pictures='+value,{pict:pict},function(response){	
		$j('#div_pictures').html(response);
	});	
}
function TemplateProfileAddPhotos(){
	var pict = $j('#nr_pictures').val();
	$j.post('?show_template_add_photos='+pict,{},function(response){
		$j('#div_pictures').html(response);
	});
}
function ShowCaptionPhoto(id,val){
	if(val==1){
		$j('#div_caption_'+id).removeClass('ascuns');		
		$j('#div_caption_'+id).addClass('field_row');	
	}else{		
		$j('#div_caption_'+id).removeClass('field_row'); 
		$j('#div_caption_'+id).addClass('ascuns');		
	} 
}
function TemplatePollsAddAwards(){
	var award = $j('#nr_awards').val();
	if(award>0){
		$j('#div_award').removeClass('ascuns'); 
		$j('#div_award').addClass('field_row');
	}
}
function ShowAward(sel,val){
	if(val==1){		
		$j('#div_award_'+sel).removeClass('ascuns');		
		$j('#div_award_'+sel).addClass('field_row');
		
		if(sel=='photo'){
			$j('#div_ratio_'+sel).removeClass('ascuns');		
			$j('#div_ratio_'+sel).addClass('field_row');			
		}		
	}else{		
		$j('#div_award_'+sel).removeClass('field_row'); 
		$j('#div_award_'+sel).addClass('ascuns');		
	} 
}
function TemplateOthersAdd(sel,type){
	$j('#div_'+sel).removeClass('ascuns');		
	$j('#div_'+sel).addClass('view');
	$j('#link_'+sel).removeClass('view');		
	$j('#link_'+sel).addClass('ascuns');
	
	if(sel=='photos'){
		var pict = $j('#nr_photos').val();
		if(pict>0){
			$j.post('?show_template_add_photos='+pict,{},function(response){
				$j('#div_'+sel).html(response);
			});
		}
	}
	if(sel=='textarea'){
		var text = $j('#nr_textarea').val();
		if(type==1 && text>3) alert("You can add a maximum of 3 Textarea");
		else if(text>0 && text<4){
			$j.post('?show_template_add_textarea='+text, {}, function(response){
				$j("#div_"+sel).html(response);
			});	
		}
	}
	if(sel=='textfield'){
		var text = $j('#nr_textfield').val();
		if(type==1 && text>5) alert("You can add a maximum of 5 Textfield");
		else if(text>0 && text<6){
			$j.post('?show_template_add_textfield='+text, {}, function(response){
				$j("#div_"+sel).html(response);
			});
		}
	}
}
function ShowCaptionPhotoOther(val){
	if(val==1){
		$j('#div_caption').removeClass('ascuns');		
		$j('#div_caption').addClass('field_row');	
	}else{		
		$j('#div_caption').removeClass('field_row'); 
		$j('#div_caption').addClass('ascuns');		
	} 
}
function ShowLinkOthers(val){
	$j('#link_'+val).removeClass('ascuns'); 
	$j('#link_'+val).addClass('');
}
function SetPreference(val){
	if(val==1){
		var books = $j('#books').val();
		var comments = $j('#comments').val();
		if(books!=''){
			$j.post(HTTP+'set_preference/1', {books:books,comments:comments}, function(response){
				if(response=='success'){
					$j('#preference2').removeClass('ascuns');		
					$j('#preference2').addClass('');
					$j('#preference1').removeClass('');		
					$j('#preference1').addClass('ascuns');	
					if(books>1) books = books+' yearbooks ';
					else books = books+' yearbook ';
					$j('#nr_books').html(books);
				} 
			});
		}
	}else{
		$j('#preference1').removeClass('ascuns');		
		$j('#preference1').addClass('');
		$j('#preference2').removeClass('');		
		$j('#preference2').addClass('ascuns');
	}
}
//montage
function TemplateAddPhoto(){
	//alert('mere');
	var pict = $j('#nr_photos').val();
	var pict1 = $j('#nr_photos1').val();
	var id_div = parseInt(pict)+1;
	var id_div1 = parseInt(pict1)+1;
	$j('#nr_photos').val(id_div);
	$j('#nr_photos1').val(id_div1);	
	$j.post('?show_template_add_photo',{id_div:id_div1,nr_div:id_div},function(response){
		//alert(id_div1);
		//alert(id_div);
		$j('#div_photos').append(response);
	});
}
function DeletePhoto(val){
	$j('#delete_picture_'+val).attr('checked', true);
	$j('#picture_'+val).html('');
	var pict = $j('#nr_photos').val();
	var pict1 = $j('#nr_photos1').val();
	pict = parseInt(pict);
	pict1 = parseInt(pict1);
	//alert('pict: '+pict);
	var x=1;	
	for(i=1;i<=pict1;i++){
		//alert('i: '+i);
		if($j('#delete_picture_'+i).val() != 1){
			//alert('da');
		}else{
			//alert('nu');
			$j('#nr_pict_'+i).html(x);
			x++;
		}
	}
	var y=pict-1;
	//alert('new pict: '+y);
	$j('#nr_photos').val(y);
}
function TemplateAddTextfield(){
	var pict = $j('#nr_textfield').val();
	var pict1 = $j('#nr_textfield1').val();	
	if(pict>4)alert("You can add a maximum of 5 Textfield");
	else{
		var pict = $j('#nr_textfield').val();
		var pict1 = $j('#nr_textfield1').val();
		var id_div = parseInt(pict)+1;
		var id_div1 = parseInt(pict1)+1;
		$j('#nr_textfield').val(id_div);
		$j('#nr_textfield1').val(id_div1);	
		$j.post('?show_template_textfield',{id_div:id_div1,nr_div:id_div},function(response){
			//alert(id_div1);
			//alert(id_div);
			$j('#div_textfield').append(response);
		});
	}
}
function DeleteTextfield(val){
	$j('#delete_textfield_'+val).attr('checked', true);
	$j('#textfield_'+val).html('');
	var pict = $j('#nr_textfield').val();
	var pict1 = $j('#nr_textfield1').val();
	pict = parseInt(pict);
	pict1 = parseInt(pict1);
	//alert('pict: '+pict);
	var x=1;	
	for(i=1;i<=pict1;i++){
		//alert('i: '+i);
		if($j('#delete_textfield_'+i).val() != 1){
			//alert('da');
		}else{
			//alert('nu');
			$j('#nr_field_'+i).html(x);
			x++;
		}
	}
	var y=pict-1;
	//alert('new pict: '+y);
	$j('#nr_textfield').val(y);
}
function TemplateAddTextarea(){
	var pict = $j('#nr_textarea').val();
	var pict1 = $j('#nr_textarea1').val();
	if(pict>2) alert("You can add a maximum of 3 Textarea");
	else{
		var pict = $j('#nr_textarea').val();
		var pict1 = $j('#nr_textarea1').val();
		var id_div = parseInt(pict)+1;
		var id_div1 = parseInt(pict1)+1;
		$j('#nr_textarea').val(id_div);
		$j('#nr_textarea1').val(id_div1);	
		$j.post('?show_template_textarea',{id_div:id_div1,nr_div:id_div},function(response){
			 //alert(id_div1);
			//alert(id_div);
			$j('#div_textarea').append(response);
		});
	}
}
function DeleteTextarea(val){
	$j('#delete_textarea_'+val).attr('checked', true);
	$j('#textarea_'+val).html('');
	var pict = $j('#nr_textarea').val();
	var pict1 = $j('#nr_textarea1').val();
	pict = parseInt(pict);
	pict1 = parseInt(pict1);
	//alert('pict: '+pict);
	var x=1;	
	for(i=1;i<=pict1;i++){
		//alert('i: '+i);
		if($j('#delete_textarea_'+i).val() != 1){
			//alert('da');
		}else{
			//alert('nu');
			$j('#nr_field_'+i).html(x);
			x++;
		}
	}
	var y=pict-1;
	$j('#nr_textarea').val(y);
}
function Step2CheckSize(value){
	$j('#div_styles').load(HTTP + 'admin.php?setup&style='+value);	
}
function Step2ActivateColorPicker(){
	if($j('#color').length>0)
	$j('#color').ColorPicker({
		onSubmit: function(hsb, hex, rgb, el) {
			$j(el).val(hex);
			$j(el).ColorPickerHide();
		},
		onBeforeShow: function () {
			$j(this).ColorPickerSetColor(this.value);
		}
	})
	.bind('keyup', function(){
		$j(this).ColorPickerSetColor(this.value);
	});
}
function Step3GroupAdd(){
	if ($j('#formStep3Add').length > 0) {
		$j('#formStep3Add').ajaxForm( {
			success : function(response) {
				if (response){	
					alert(response);
					if(response == 'success'){
						tb_show('',HTTP+'admin.php?setup&add_group_step2&resize=true&height=530&width=700&modal=true',false);
					}else{						
						alert(response);
					}
				}
			}
		});
	}
}
function Step3GroupEdit(){
	if ($j('#formStep3Add').length > 0) {
		$j('#formStep3Add').ajaxForm( {
			success : function(response) {
				if (response){	
					var value = $j('#group_id').val();	
					if(response == 'success'){
						tb_show('',HTTP+'admin.php?setup&edit_group_step2='+value+'&resize=true&height=530&width=700&modal=true',false);
					}else{						
						alert(response);
					}
				}
			}
		});
	}
}
function Step3GroupAddStep2(){
	if ($j('#formStep3Add').length > 0) {
		$j('#formStep3Add').ajaxForm( {
			success : function(response) {
				if (response){	
					//alert(response);
					if(response == 'success'){						
						tb_show('',HTTP+'admin.php?setup&add_group_step3&resize=true&height=430&width=450&modal=true',false);
					}else{						
						alert(response);
					}
				}
			}
		});
	}
}

function Step3GroupAddStep3(){
	if ($j('#formStep3Add').length > 0) {
		$j('#formStep3Add').ajaxForm( {
			success : function(response) {
				if (response){	
					//alert(response);
					if(response == 'success'){
						document.location=HTTP+'admin.php?setup&step3';
						//tb_show('',HTTP+'setup/add_group_step3?resize=true&height=430&width=450&modal=true',false);
					}else{						
						alert(response);
					}
				}
			}
		});
	}
}
function Step3GroupEditStep3(){
	if ($j('#formStep3Add').length > 0) {
		$j('#formStep3Add').ajaxForm( {
			success : function(response) {
				if (response){	
					if(response == 'success'){
						document.location=HTTP+'admin.php?setup&step3';
						//tb_show('',HTTP+'setup/add_group_step3?resize=true&height=430&width=450&modal=true',false);
					}else{						
						alert(response);
					}
				}
			}
		});
	}
}
function Step3GroupAddNew(){
	if ($j('#formStep3Addg').length > 0) {
		$j('#formStep3Addg').ajaxForm( {
			success : function(response) {
				if (response){alert(response);
					if(response =='1' || response =='2'){
						if(response == '1')
							document.location=HTTP+'admin.php?setup&step3';
						else if(response == '2')
							tb_show('',HTTP+'admin.php?setup&add_group_step2&resize=true&height=530&width=700&modal=true',false);
					}else{
						alert(response);					
					}
				}
			}
		});
	}
}
function AddGroupAddComponent(){
	var nr_comp = $j('#nr_comp').val();
	nr_comp++;
	$j('#nr_comp').val(nr_comp);
	var value = $j('#add_name').val();	
	if(value!=''){		
		$j('#div_comp').append('<div class="group_add_comp6"><div id="comp_'+nr_comp+'" class="group_add_comp6_title">'+value+'</div><div class="group_add_comp6_opt"><input type="checkbox" id="include_'+nr_comp+'" name="include_'+nr_comp+'" onclick="AddGroupIncludeComponent('+nr_comp+');" />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="checkbox" id="index_'+nr_comp+'" name="index_'+nr_comp+'" onclick="AddGroupIndexComponent('+nr_comp+');"/></div></div>');
		$j('#add_name').val('');	
	}		
}
function AddGroupIncludeComponent(value){
	var content = $j('#comp_'+value).html();	
	$j.post(HTTP+'admin.php?setup&add_component',{component:content,type:1},function(response){
		if(response != 'success') alert(response);		
	});
}
function AddGroupIndexComponent(value){	
	var content = $j('#comp_'+value).html();	
	$j.post(HTTP+'admin.php?setup&add_component',{component:content,type:2},function(response){
		if(response != 'success') alert(response);		
	});
}
function GroupAddShowTab(value){
	for(i=1;i<4;i++){
		$j('#tab'+i).removeClass('group_add_tab_over');		
		$j('#tab'+i).addClass('group_add_tab');
		$j('#content'+i).removeClass('');		
		$j('#content'+i).addClass('ascuns');
	}
	$j('#tab'+value).removeClass('group_add_tab');		
	$j('#tab'+value).addClass('group_add_tab_over');
	$j('#content'+value).removeClass('ascuns');		
	$j('#content'+value).addClass('');	
}
function AddGroupAddQuestionRecom(value){
	var nr_quest_recom = $j('#nr_quest_recom').val();
	nr_quest_recom++;
	$j('#nr_quest_recom').val(nr_quest_recom);
	$j('#nr_recom_question').html(nr_quest_recom);
	var content = $j('#quest_'+value+'_cont').html();
	$j('#quest_'+value).remove();
	$j('#div_quest_recom').append('<div id="quest_recom_'+value+'" class="group_add_comp10_line"><div id="quest_recom_'+value+'_cont" class="group_add_comp10_title">'+content+'</div><div class="group_add_comp10_opt"><strong><a href="#" onclick="AddGroupDeleteQuestionRecom('+value+')">remove</a></strong></div></div>');
	$j.post(HTTP+'admin.php?setup&add_question',{question:content,mandatory:1},function(response){
		if(response != 'success') alert(response);		
	});
}
function AddGroupAddQuestionOpt(value){	
	var nr_quest_opt = $j('#nr_quest_opt').val();
	nr_quest_opt++;
	$j('#nr_quest_opt').val(nr_quest_opt);
	$j('#nr_opt_question').html(nr_quest_opt);
	var content = $j('#quest_'+value+'_cont').html();
	$j('#quest_'+value).remove();
	$j('#div_quest_opt').append('<div id="quest_opt_'+value+'" class="group_add_comp10_line"><div id="quest_opt_'+value+'_cont" class="group_add_comp10_title">'+content+'</div><div class="group_add_comp10_opt"><strong><a href="#" onclick="AddGroupDeleteQuestionOpt('+value+')">remove</a></strong></div></div>');
	$j.post(HTTP+'admin.php?setup&add_question',{question:content,mandatory:0},function(response){
		if(response != 'success') alert(response);
	});
}
function AddGroupAddNewQeustion(value){
	var content = $j('#add_question').val();
	$j('#add_question').val('');
	var nr_quest = $j('#nr_quest').val();
	if(content!=''){		
		if(value == 1){
			var nr_quest_recom = $j('#nr_quest_recom').val();
			nr_quest_recom++;
			$j('#nr_quest_recom').val(nr_quest_recom);
			var nr_quest = $j('#nr_quest').val();
			nr_quest++;
			$j('#nr_quest').val(nr_quest);
			$j('#nr_recom_question').html(nr_quest_recom);
			$j('#div_quest_recom').append('<div id="quest_recom_'+nr_quest+'" class="group_add_comp10_line"><div id="quest_recom_'+nr_quest+'_cont" class="group_add_comp10_title">'+content+'</div><div class="group_add_comp10_opt"><strong><a href="#" onclick="AddGroupDeleteQuestionRecom('+nr_quest+')">remove</a></strong></div></div>');
			$j.post(HTTP+'admin.php?setup&add_question',{question:content,mandatory:1},function(response){
				if(response != 'success') alert(response);
			});
		}else if(value == 2){
			var nr_quest_opt = $j('#nr_quest_opt').val();
			nr_quest_opt++;
			$j('#nr_quest_opt').val(nr_quest_opt);
			var nr_quest = $j('#nr_quest').val();
			nr_quest++;
			$j('#nr_quest').val(nr_quest);
			$j('#nr_opt_question').html(nr_quest_opt);
			$j('#div_quest_opt').append('<div id="quest_opt_'+nr_quest+'" class="group_add_comp10_line"><div id="quest_opt_'+nr_quest+'_cont" class="group_add_comp10_title">'+content+'</div><div class="group_add_comp10_opt"><strong><a href="#" onclick="AddGroupDeleteQuestionOpt('+nr_quest+')">remove</a></strong></div></div>');
			$j.post(HTTP+'admin.php?setup&add_question',{question:content,mandatory:0},function(response){
				if(response != 'success') alert(response);
			});
		}	
	}
}
function AddGroupDeleteQuestionRecom(value){
	var nr_quest_recom = $j('#nr_quest_recom').val();
	nr_quest_recom--;
	$j('#nr_quest_recom').val(nr_quest_recom);
	$j('#nr_recom_question').html(nr_quest_recom);		
	var content = $j('#quest_recom_'+value+'_cont').html();
	$j('#quest_recom_'+value).remove();
	$j('#div_quest').append('<div id="quest_'+value+'" class="group_add_comp11_line"><div id="quest_'+value+'_cont" class="group_add_comp11_title">'+content+'</div><div class="group_add_comp11_opt"><strong><img src="'+HTTP+'_layouts/images/icon_r.png" border="0" alt="" onclick="AddGroupAddQuestionRecom('+value+')"/><img src="'+HTTP+'_layouts/images/icon_o.png" border="0" alt="" onclick="AddGroupAddQuestionOpt('+value+')"/></strong></div></div>');
	$j.post(HTTP+'admin.php?setup&delete_question',{question:content,mandatory:1},function(response){
		if(response != 'success') alert(response);		
	});
}
function AddGroupDeleteQuestionOpt(value){	
	var nr_quest_opt = $j('#nr_quest_opt').val();
	nr_quest_opt--;
	$j('#nr_quest_opt').val(nr_quest_opt);
	$j('#nr_opt_question').html(nr_quest_opt);	
	var content = $j('#quest_opt_'+value+'_cont').html();
	$j('#quest_opt_'+value).remove();
	$j('#div_quest').append('<div id="quest_'+value+'" class="group_add_comp11_line"><div id="quest_'+value+'_cont" class="group_add_comp11_title">'+content+'</div><div class="group_add_comp11_opt"><strong><img src="'+HTTP+'_layouts/images/icon_r.png" border="0" alt="" onclick="AddGroupAddQuestionRecom('+value+')"/><img src="'+HTTP+'_layouts/images/icon_o.png" border="0" alt="" onclick="AddGroupAddQuestionOpt('+value+')"/></strong></div></div>');
	$j.post(HTTP+'admin.php?setup&delete_question',{question:content,mandatory:0},function(response){
		if(response != 'success') alert(response);		
	});
}
function AddGroupAddTopicRecom(value){
	var nr_topic_recom = $j('#nr_topic_recom').val();
	nr_topic_recom++;
	$j('#nr_topic_recom').val(nr_topic_recom);
	$j('#nr_recom_topic').html(nr_topic_recom);
	var content = $j('#topic_'+value+'_cont').html();
	$j('#topic_'+value).remove();
	$j('#div_topic_recom').append('<div id="topic_recom_'+value+'" class="group_add_comp10_line"><div id="topic_recom_'+value+'_cont" class="group_add_comp10_title">'+content+'</div><div class="group_add_comp10_opt"><strong><a href="#" onclick="AddGroupDeleteTopicRecom('+value+')">remove</a></strong></div></div>');
	$j.post(HTTP+'admin.php?setup&add_topic',{topic:content,mandatory:1},function(response){
		if(response != 'success') alert(response);		
	});
}
function AddGroupAddTopicOpt(value){	
	var nr_topic_opt = $j('#nr_topic_opt').val();
	nr_topic_opt++;
	$j('#nr_topic_opt').val(nr_topic_opt);
	$j('#nr_opt_topic').html(nr_topic_opt);
	var content = $j('#topic_'+value+'_cont').html();
	$j('#topic_'+value).remove();
	$j('#div_topic_opt').append('<div id="topic_opt_'+value+'" class="group_add_comp10_line"><div id="topic_opt_'+value+'_cont" class="group_add_comp10_title">'+content+'</div><div class="group_add_comp10_opt"><strong><a href="#" onclick="AddGroupDeleteTopicOpt('+value+')">remove</a></strong></div></div>');
	$j.post(HTTP+'admin.php?setup&add_topic',{topic:content,mandatory:0},function(response){
		if(response != 'success') alert(response);
	});
}
function AddGroupAddNewTopic(value){
	var content = $j('#add_topic').val();
	$j('#add_topic').val('');
	var nr_topic = $j('#nr_topic').val();
	if(content!=''){		
		if(value == 1){
			var nr_topic_recom = $j('#nr_topic_recom').val();
			nr_topic_recom++;
			$j('#nr_topic_recom').val(nr_topic_recom);
			var nr_topic = $j('#nr_topic').val();
			nr_topic++;
			$j('#nr_topic').val(nr_topic);
			$j('#nr_recom_topic').html(nr_topic_recom);
			$j('#div_topic_recom').append('<div id="topic_recom_'+nr_topic+'" class="group_add_comp10_line"><div id="topic_recom_'+nr_topic+'_cont" class="group_add_comp10_title">'+content+'</div><div class="group_add_comp10_opt"><strong><a href="#" onclick="AddGroupDeleteTopicRecom('+nr_topic+')">remove</a></strong></div></div>');
			$j.post(HTTP+'admin.php?setup&add_topic',{topic:content,mandatory:1},function(response){
				if(response != 'success') alert(response);
			});
		}else if(value == 2){
			var nr_topic_opt = $j('#nr_topic_opt').val();
			nr_topic_opt++;
			$j('#nr_topic_opt').val(nr_topic_opt);
			var nr_topict = $j('#nr_topic').val();
			nr_topic++;
			$j('#nr_topic').val(nr_topic);
			$j('#nr_opt_topic').html(nr_topic_opt);
			$j('#div_topic_opt').append('<div id="topic_opt_'+nr_topic+'" class="group_add_comp10_line"><div id="topic_opt_'+nr_topic+'_cont" class="group_add_comp10_title">'+content+'</div><div class="group_add_comp10_opt"><strong><a href="#" onclick="AddGroupDeleteTopicOpt('+nr_topic+')">remove</a></strong></div></div>');
			$j.post(HTTP+'admin.php?setup&add_topic',{topic:content,mandatory:0},function(response){
				if(response != 'success') alert(response);
			});
		}	
	}
}
function AddGroupDeleteTopicRecom(value){
	var nr_topic_recom = $j('#nr_topic_recom').val();
	nr_topic_recom--;
	$j('#nr_topic_recom').val(nr_topic_recom);
	$j('#nr_recom_topic').html(nr_topic_recom);		
	var content = $j('#topic_recom_'+value+'_cont').html();
	$j('#topic_recom_'+value).remove();
	$j('#div_topic').append('<div id="topic_'+value+'" class="group_add_comp11_line"><div id="topic_'+value+'_cont" class="group_add_comp11_title">'+content+'</div><div class="group_add_comp11_opt"><strong><img src="'+HTTP+'_layouts/images/icon_r.png" border="0" alt="" onclick="AddGroupAddTopicRecom('+value+')"/><img src="'+HTTP+'_layouts/images/icon_o.png" border="0" alt="" onclick="AddGroupAddTopicOpt('+value+')"/></strong></div></div>');
	$j.post(HTTP+'admin.php?setup&delete_topic',{topic:content,mandatory:1},function(response){
		if(response != 'success') alert(response);		
	});
}
function AddGroupDeleteTopicOpt(value){	
	var nr_topic_opt = $j('#nr_topic_opt').val();
	nr_topic_opt--;
	$j('#nr_topic_opt').val(nr_topic_opt);
	$j('#nr_opt_topic').html(nr_topic_opt);	
	var content = $j('#topic_opt_'+value+'_cont').html();
	$j('#topic_opt_'+value).remove();
	$j('#div_topic').append('<div id="topic_'+value+'" class="group_add_comp11_line"><div id="topic_'+value+'_cont" class="group_add_comp11_title">'+content+'</div><div class="group_add_comp11_opt"><strong><img src="'+HTTP+'_layouts/images/icon_r.png" border="0" alt="" onclick="AddGroupAddTopicRecom('+value+')"/><img src="'+HTTP+'_layouts/images/icon_o.png" border="0" alt="" onclick="AddGroupAddTopicOpt('+value+')"/></strong></div></div>');
	$j.post(HTTP+'admin.php?setup&delete_topic',{topic:content,mandatory:0},function(response){
		if(response != 'success') alert(response);		
	});
}
function ChangeDeadline(){
	if ($j('#frmEdit').length > 0) {
		$j('#frmEdit').ajaxForm({
			success : function(response) {
				if (response){	
					$j('#div_deadline').html(response);
					tb_remove();
				}else tb_remove();
			}
		});
	}
	if ($j("#deadline").length > 0) {
		$j("#deadline").datepicker({
					changeFirstDay: false,
					dateFormat: 'dd/mm/yy',
					showOn: 'both',
					buttonImage: HTTP+'_layouts/images/calendar1.gif',
					buttonImageOnly: true,
					yearRange: '1930:2030',
					defaultDate: new Date ()
				});
	}
}