function hasOptions(obj){if(obj!=null && obj.options!=null){return true;}return false;}
function selectUnselectMatchingOptions(obj,regex,which,only){if(window.RegExp){if(which == "select"){var selected1=true;var selected2=false;}else if(which == "unselect"){var selected1=false;var selected2=true;}else{return;}var re = new RegExp(regex);if(!hasOptions(obj)){return;}for(var i=0;i<obj.options.length;i++){if(re.test(obj.options[i].text)){obj.options[i].selected = selected1;}else{if(only == true){obj.options[i].selected = selected2;}}}}}
function selectMatchingOptions(obj,regex){selectUnselectMatchingOptions(obj,regex,"select",false);}
function selectOnlyMatchingOptions(obj,regex){selectUnselectMatchingOptions(obj,regex,"select",true);}
function unSelectMatchingOptions(obj,regex){selectUnselectMatchingOptions(obj,regex,"unselect",false);}
function sortSelect(obj){var o = new Array();if(!hasOptions(obj)){return;}for(var i=0;i<obj.options.length;i++){o[o.length] = new Option( obj.options[i].text, obj.options[i].value, obj.options[i].defaultSelected, obj.options[i].selected) ;}if(o.length==0){return;}o = o.sort(
function(a,b){if((a.text+"") <(b.text+"")){return -1;}if((a.text+"") >(b.text+"")){return 1;}return 0;});for(var i=0;i<o.length;i++){obj.options[i] = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);}}
function selectAllOptions(obj){if(!hasOptions(obj)){return;}for(var i=0;i<obj.options.length;i++){obj.options[i].selected = true;}}
function moveSelectedOptions(from,to){if(arguments.length>3){var regex = arguments[3];if(regex != ""){unSelectMatchingOptions(from,regex);}}if(!hasOptions(from)){return;}for(var i=0;i<from.options.length;i++){var o = from.options[i];if(o.selected){if(!hasOptions(to)){var index = 0;}else{var index=to.options.length;}to.options[index] = new Option( o.text, o.value, false, false);}}for(var i=(from.options.length-1);i>=0;i--){var o = from.options[i];if(o.selected){from.options[i] = null;}}if((arguments.length<3) ||(arguments[2]==true)){sortSelect(from);sortSelect(to);}from.selectedIndex = -1;to.selectedIndex = -1;}
function copySelectedOptions(from,to){var options = new Object();if(hasOptions(to)){for(var i=0;i<to.options.length;i++){options[to.options[i].value] = to.options[i].text;}}if(!hasOptions(from)){return;}for(var i=0;i<from.options.length;i++){var o = from.options[i];if(o.selected){if(options[o.value] == null || options[o.value] == "undefined" || options[o.value]!=o.text){if(!hasOptions(to)){var index = 0;}else{var index=to.options.length;}to.options[index] = new Option( o.text, o.value, false, false);}}}if((arguments.length<3) ||(arguments[2]==true)){sortSelect(to);}from.selectedIndex = -1;to.selectedIndex = -1;}
function moveAllOptions(from,to){selectAllOptions(from);if(arguments.length==2){moveSelectedOptions(from,to);}else if(arguments.length==3){moveSelectedOptions(from,to,arguments[2]);}else if(arguments.length==4){moveSelectedOptions(from,to,arguments[2],arguments[3]);}}
function copyAllOptions(from,to){selectAllOptions(from);if(arguments.length==2){copySelectedOptions(from,to);}else if(arguments.length==3){copySelectedOptions(from,to,arguments[2]);}}
function swapOptions(obj,i,j){var o = obj.options;var i_selected = o[i].selected;var j_selected = o[j].selected;var temp = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);var temp2= new Option(o[j].text, o[j].value, o[j].defaultSelected, o[j].selected);o[i] = temp2;o[j] = temp;o[i].selected = j_selected;o[j].selected = i_selected;}
function moveOptionUp(obj){if(!hasOptions(obj)){return;}for(i=0;i<obj.options.length;i++){if(obj.options[i].selected){if(i != 0 && !obj.options[i-1].selected){swapOptions(obj,i,i-1);obj.options[i-1].selected = true;}}}}
function moveOptionDown(obj){if(!hasOptions(obj)){return;}for(i=obj.options.length-1;i>=0;i--){if(obj.options[i].selected){if(i !=(obj.options.length-1) && ! obj.options[i+1].selected){swapOptions(obj,i,i+1);obj.options[i+1].selected = true;}}}}
function removeSelectedOptions(from){if(!hasOptions(from)){return;}if(from.type=="select-one"){from.options[from.selectedIndex] = null;}else{for(var i=(from.options.length-1);i>=0;i--){var o=from.options[i];if(o.selected){from.options[i] = null;}}}from.selectedIndex = -1;}
function removeAllOptions(from){if(!hasOptions(from)){return;}for(var i=(from.options.length-1);i>=0;i--){from.options[i] = null;}from.selectedIndex = -1;}
function addOption(obj,text,value,selected){if(obj!=null && obj.options!=null){obj.options[obj.options.length] = new Option(text, value, false, selected);}}


function getTurns(planID, z)
{
	//alert(planID);
	
	var list = document.getElementById('list21');
	var len = list.length;
	
	//alert(list.options[1].value);

	str='';
	for(var x=0; x<len; x++)	{
		if(list.options[x].value == '')
			list.options[x].value = 0;
			
		str = str  +"*"+list.options[x].value  ;
	}
	
	if(z == 1)
		add = 'option_box.php?saveTurns=1&planID='+planID+ '&turns='+str;		//used when the plan is active and the turns have to be changed
	else
		add = 'start_plan.php?saveTurns=1&planID='+planID+ '&turns='+str;
	openLink(add);
	
	//alert(str);
}

function Confirm(planID)
{
	var x = confirm("You are about to start this plan, do you want to continue?");
	if(x)	{	//start the plan
		//location.href= 'start_plan.php?StartPlan=1&planID=' + planID;
		openLink= 'start_plan.php?StartPlan=1&planID=' + planID;
		}
}

function confirmBankDelete(userID, bankID)
{
	var x = confirm("Do you really want to remove your bank information?");
	if(x){
		//location.href= 'acc_settings.php?deleteBank=1&userID=' + userID + '&bankID=' + bankID;
		openLink= 'acc_settings.php?deleteBank=1&userID=' + userID + '&bankID=' + bankID;
		}
}

function verifyBank(userID, bankID)
{
	url = 'bank_verify.php';
	newwindow=window.open(url,'name','height=150,width=300');
	if (window.focus) {newwindow.focus()}
		return false;
}

function getXMLHttp()
{
  var xmlHttp

  try
  {
    //Firefox, Opera 8.0+, Safari
    xmlHttp = new XMLHttpRequest();
  }
  catch(e)
  {
    //Internet Explorer
    try
    {
      xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(e)
    {
      try
      {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch(e)
      {
        alert("Your browser does not support AJAX!")
        return false;
      }
    }
  }
  return xmlHttp;
}


function getVendorByType(type)
{
  var xmlHttp = getXMLHttp();
  
  xmlHttp.onreadystatechange = function()
  {
    if(xmlHttp.readyState == 4)
    {
		showVendor(xmlHttp.responseText);
    }
  }
  
var str = "ajax.php?script=getVendorByType&vendor_type=" + type;
  xmlHttp.open("GET", str, true); 
  xmlHttp.send(null);
}


function getVendorInfo(turnID, planID)
{
  var xmlHttp = getXMLHttp();
  
  xmlHttp.onreadystatechange = function()
  {
    if(xmlHttp.readyState == 4)
    {
		showVendor(xmlHttp.responseText);
    }
  }
  
var str = "ajax.php?script=getVendorInfo&turnID=" + turnID + "&planID=" + planID;
  xmlHttp.open("GET", str, true); 
  xmlHttp.send(null);
}

function showVendor(str)
{
	document.getElementById('vendorDiv').innerHTML = str;
}

function openLink(link)
{
	var xmlHttp = getXMLHttp();
	
	xmlHttp.onreadystatechange = function()
	{
		if(xmlHttp.readyState == 4)
			showLink(xmlHttp.responseText);
	}

	xmlHttp.open("GET", link, true); 
	xmlHttp.send(null);
}

function showLink(response)
{
	document.getElementById('body_main_content').innerHTML = response;
	//alert("main");
	
}

function openLink_side(link)
{
	var xmlHttp = getXMLHttp();
	
	xmlHttp.onreadystatechange = function()
	{
		if(xmlHttp.readyState == 4)
			showLink_side(xmlHttp.responseText);
	}

	xmlHttp.open("GET", link, true); 
	xmlHttp.send(null);
}

function showLink_side(response)
{
	document.getElementById('body_sidebar_content').innerHTML = response;
	//alert("side");
	//parseScript(response);
}

function parseScript(_source) {
	var source = _source;
	var scripts = new Array();
	
	// Strip out tags
	while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
		var s = source.indexOf("<script");
		var s_e = source.indexOf(">", s);
		var e = source.indexOf("</script", s);
		var e_e = source.indexOf(">", e);
		
		// Add to scripts array
		scripts.push(source.substring(s_e+1, e));
		// Strip from source
		source = source.substring(0, s) + source.substring(e_e+1);
	}
	
	// Loop through every script collected and eval it
	for(var i=0; i<scripts.length; i++) {
		try {
			eval(scripts[i]);
			//alert(scripts[i]);
		}
		catch(ex) {
			alert(scripts[i]);
		}
	}
	
	// Return the cleaned source
	return source;
}

//--------------------------------------
function createRequestObject(){
   if(window.XMLHttpRequest) {
      return new XMLHttpRequest(); // IE 7, Firefox, Safari, Opera...
   }
   else if(window.ActiveXObject) {
      return new ActiveXObject("Microsoft.XMLHTTP"); // Internet Explorer 6, 5
   }
   else { alert('Problem creating the XMLHttpRequest object'); }
   return false;
}
 
function ajaxFormSubmit(form, button){
//alert(button);
	var params = getParams(form, button);
	var action = form.getAttribute('action');
	//alert('action:' + action + params);
	alert(action + params);
	var httpRequest = createRequestObject();
	if(!httpRequest) return false;
	httpRequest.onreadystatechange = function() {
		if(httpRequest.readyState == 4) {
		//alert('response');
			//Here do whatever you need to with the response (httpRequest.responseText)
			document.getElementById('body_main_content').innerHTML = httpRequest.responseText;//for example
		}
	}
	httpRequest.open('POST', action + params, true);
	//httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	httpRequest.setRequestHeader("Content-type", "multipart/form-data");//Possible alternative?
	httpRequest.setRequestHeader("Content-length", params.length);
	httpRequest.setRequestHeader("Connection", "close");
	httpRequest.send(params);
	return false;
}

function getParams(form, button) {
	var params = [];
	for (i=0; i<form.elements.length; i++){
		var e = form.elements[i];
		var n = e.getAttribute('name');
		if (!n) continue;
		if (e.tagName == "INPUT"){
			switch (e.getAttribute('type')){
				case "text":
					params.push(n + "=" + URLEncode(e.value));
				break;
				case "password":
					params.push(n + "=" + URLEncode(e.value));
				break;
				case "checkbox":
					if (e.checked) { params.push(n + "=" + URLEncode(e.value)); }
				break;
				case "radio":
					if (e.checked) { params.push(n + "=" + URLEncode(e.value)); }
				break;
				case "hidden":
					params.push(n + "=" + URLEncode(e.value));
				break;
				//case "submit":
					//alert(e.clicked.value);
					//{params.push(URLEncode(e.value));}
					//params.push(n);	
				//default:
				
				break;
			}
		}
		if (e.tagName == "TEXTAREA"){
			params.push(n + "=" + URLEncode(e.value));
		}
		if (e.tagName == "SELECT"){
		//alert(n);
			params.push(n + "=" + URLEncode(e.options[e.selectedIndex].value));
		}
		//if (e.tagName == "BUTTON"){
			//params.push(n + "=" + URLEncode(e.value));
		//}
	}
	params.push(button);
	var str = '?' + params.join('&');
	//var str = params.join('&');
	//alert(str);
	return str;
}

function URLEncode(clearString){
	// Encode strings to be compatible with php's urldecode().
	// Based on "Javascript URL encoding and decoding", http://cass-hacks.com/articles/code/js_url_encode_decode/
	if(!Number.toString) { return clearString; }//Very old browsers
	var output = [];
	var x = 0;
	clearString = clearString.toString();
	var regex = /(^[a-zA-Z0-9_.]*)/;
	while (x < clearString.length) {
		var match = regex.exec(clearString.substr(x));
		if (match != null && match.length > 1 && match[1] != '') {
			output.push(match[1]);
			x += match[1].length;
		}
		else {
			if (clearString.substr(x,1) == ' '){ output.push('+'); }
			else {
				var charCode = clearString.charCodeAt(x);
				var hexVal = charCode.toString(16);
				output.push('%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase());
			}
			x++;
	    }
	}
	return output.join('');
}

function distribute(focusBox, totAmnt)
{
	if(focusBox.name == 'cardAmnt')	{
		document.getElementById('cashAmnt').value = (totAmnt - focusBox.value);
	}
	else
		document.getElementById('cardAmnt').value = (totAmnt - focusBox.value);
}

function show()
{
	//alert(document.getElementById('period').value);	
	if(document.getElementById('period').value == 'other')
		document.getElementById('box').innerHTML = "<input type='text' name='period' size='5'></input> &nbsp Days";
	else
		document.getElementById('box').innerHTML = "";
}

function checkAll()
{
	nb = document.all.item('friends').length;
	if(document.getElementById('checkall').checked==true)
		check = true;
	else
		check = false;
	
	for(i=0; i<nb; i++) {
        document.all.item('friends')[i].checked=check;
    }
}

function validate_goals()
{
	var array = ["name", "date", "totalAmnt", "amnt"];
	var array2 = ["Name", "Date", "Total Amount", "Amount"];
	
	for(var i in array)
	if(document.getElementById(array[i]).value == '' ){
		alert("The "+ array2[i] + " field cannot be empty");
		return false;
	}
	return true;
}

function validate_plans()
{
	var array = ["startDate", "totalAmnt", "members", "period"];
	var array2 = ["Start Date", "Total Amount", "Members", "Period"];
	//alert(document.getElementById('members').value);
	
	for(i in array)	{
			
		if(array[i] == 'members')
			if(document.getElementById(array[i]).value <2)	{
				alert("You should have at least 2 members in a plan");
				return false;
				}
		
		if(array[i] == 'period')
			if(document.getElementById(array[i]).value <1)	{
				alert("The length of a turn cannot be less than a day");
				return false;
				}
		
		if(array[i] == 'window')	{
			var limit = document.getElementById('windowLimit').value.trim();
			var val = document.getElementById(array[i]).value.trim();
			
			if(val>limit)	{
				alert("The payment window must be within the range specified");
				return false;
				}
			if(document.getElementById(array[i]).value=='')
				document.getElementById(array[i]).value=1;
		
		}
		
		if(document.getElementById(array[i]).value == '')	{
			alert("The "+ array2[i] + " field cannot be empty");
			return false;
			}
	}
	return 1;
}

function validate_signup()
{
	return true;
	var array = ["email", "password", "cPassword", "fName", "lName"];
	var array2 = ["Email", "Password", "Confirm Password", "First Name", "Last Name"];
	
	for(var i in array)
	if(document.getElementById(array[i]).value == '')	{
		alert(document.getElementById(array[i]).value);
		alert("The "+ array2[i] + " field cannot be empty");
		return false;
	}
	return true;
}

function validate_partners()
{
	return true;
}


function Delete(obj, planID)		//delete plan member
{
	var id = obj.name;
	if(confirm("You are about to remove this user from the Plan, do you want to continue?"))		//delete the number
	{
		//document.all.friendsList.deleteRow(2);		//visually remove row from the dash
		//location.href='plan_dash.php?deleteUser='+id +'&planID='+<?php echo $planID?>;
		openLink('plan_dash.php?deleteUser='+id +'&planID_delete='+ planID);
	}
}

//*********************TOOLTIP
var tooltip=function(){
	var id = 'tt';
	var top = 3;
	var left = 3;
	var maxw = 300;
	var speed = 10;
	var timer = 20;
	var endalpha = 95;
	var alpha = 0;
	var tt,t,c,b,h;
	var ie = document.all ? true : false;
	return{
		show:function(v,w){
			if(tt == null){
				tt = document.createElement('div');
				tt.setAttribute('id',id);
				t = document.createElement('div');
				t.setAttribute('id',id + 'top');
				c = document.createElement('div');
				c.setAttribute('id',id + 'cont');
				b = document.createElement('div');
				b.setAttribute('id',id + 'bot');
				tt.appendChild(t);
				tt.appendChild(c);
				tt.appendChild(b);
				document.body.appendChild(tt);
				tt.style.opacity = 0;
				tt.style.filter = 'alpha(opacity=0)';
				document.onmousemove = this.pos;
			}
			tt.style.display = 'block';
			c.innerHTML = v;
			tt.style.width = w ? w + 'px' : 'auto';
			if(!w && ie){
				t.style.display = 'none';
				b.style.display = 'none';
				tt.style.width = tt.offsetWidth;
				t.style.display = 'block';
				b.style.display = 'block';
			}
			if(tt.offsetWidth > maxw){tt.style.width = maxw + 'px'}
			h = parseInt(tt.offsetHeight) + top;
			clearInterval(tt.timer);
			tt.timer = setInterval(function(){tooltip.fade(1)},timer);
		},
		pos:function(e){
			var u = ie ? event.clientY + document.documentElement.scrollTop : e.pageY;
			var l = ie ? event.clientX + document.documentElement.scrollLeft : e.pageX;
			tt.style.top = (u - h) + 'px';
			tt.style.left = (l + left) + 'px';
		},
		fade:function(d){
			var a = alpha;
			if((a != endalpha && d == 1) || (a != 0 && d == -1)){
				var i = speed;
				if(endalpha - a < speed && d == 1){
					i = endalpha - a;
				}else if(alpha < speed && d == -1){
					i = a;
				}
				alpha = a + (i * d);
				tt.style.opacity = alpha * .01;
				tt.style.filter = 'alpha(opacity=' + alpha + ')';
			}else{
				clearInterval(tt.timer);
				if(d == -1){tt.style.display = 'none'}
			}
		},
		hide:function(){
			clearInterval(tt.timer);
			tt.timer = setInterval(function(){tooltip.fade(-1)},timer);
		}
	};
}();
