// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
function manageStateOptions(id){
	if(id == 1){
		document.getElementById('address_state_field').style.display = 'none';
		document.getElementById('address_state').style.display = '';
		document.getElementById('country_row').style.display = 'none';
		document.getElementById('address_country').value = 'USA';
	}
	else{
		document.getElementById('address_state').style.display = 'none';
		document.getElementById('address_state_field').style.display = '';
		document.getElementById('country_row').style.display = '';
		document.getElementById('address_country').value = '';
	}
}
function addFavourite(vendorId){
	new Ajax.Updater('update_vendors', 
					 '/account/update_fav/'+vendorId+'?action_do=1', 
					 {asynchronous:true, evalScripts:true, parameters:$('search_form').serialize(true)}
					 );
	 
}
function remFavourite(vendorId){
	new Ajax.Updater('update_vendors', 
					 '/account/update_fav/'+vendorId+'?action_do=2', 
					 {asynchronous:true, evalScripts:true, parameters:$('search_form').serialize(true)}
					 );
}
function showFav(){
	document.getElementById('no_link').className = "show-fav";
	document.getElementById('yes_link').className = "show-fav1";
	new Ajax.Updater('update_vendors', 
					 '/account/update_fav/?action_do=3', 
					 {asynchronous:true, evalScripts:true, parameters:$('search_form').serialize(true)}
					 );
}
function showAllVendors(){
	document.getElementById('no_link').className = "show-fav1";
	document.getElementById('yes_link').className = "show-fav";
	new Ajax.Updater('update_vendors', 
					 '/account/update_fav/', 
					 {asynchronous:true, evalScripts:true, parameters:$('search_form').serialize(true)}
					 );
}
//Validates Create Rfp page
function validateRFPForm()
{
	var projectName = document.getElementById('auction_project');
	var yourName = document.getElementById('auction_consumername');
	var email = document.getElementById('auction_email_address');
	var rangeCheckValue = document.getElementById('range').value;
	
	if(trim(projectName.value).length == 0)
	{
		alert("Project Name can't be blank");
		projectName.focus();
		return false;
	}
	if(trim(yourName.value).length == 0)
	{
		alert("Your Name can't be blank");
		yourName.focus();
		return false;
	}
	if(trim(email.value).length == 0)
	{
		alert("Email address can't be blank");
		email.focus();
		return false;
	}	
	if(parseInt(rangeCheckValue))
	{
		var startRange = document.getElementById('auction_price_range_from');
		var endRange = document.getElementById('auction_price_range_to');		
		if(parseFloat(startRange.value) <= 0)
		{
			alert("Start range should be greater than zero");
			startRange.focus();
			return false;
		}
		if(parseFloat(endRange.value) <= 0)
		{
			alert("End range should be greater than zero");
			endRange.focus();
			return false;
		}
		if( (parseFloat(startRange.value) > 0) && (parseFloat(endRange.value) > 0) && (parseFloat(endRange.value) < parseFloat(startRange.value)) )
		{
			alert("End range should be greater than Start Range");
			endRange.focus();
			return false;
		}
	}
	else
	{
		var askingPrice = document.getElementById('auction_asking_price');
		if(trim(askingPrice.value).length == 0)
		{
			alert("Budgeted Amount Can't be blank");
			askingPrice.focus();
			return false;
		}
		if(trim(askingPrice.value).length > 0 && parseFloat(askingPrice.value) <= 0)
		{
			alert("Budgeted Amount should be greater than zero");
			askingPrice.focus();
			return false;
		}
	}
}
//for show/hide details on show_rfps page
function SelectedVendors(vendor)
{
	if(vendor.checked)
	{
		new Ajax.Request('/account/select_vendor/?selected_vendor='+vendor.value+'&selected=1');
	}
	else
		new Ajax.Request('/account/select_vendor/?selected_vendor='+vendor.value+'&selected=0');
}

function show(id)
	{
		if( document.getElementById("row"+id).style.display == "none" )
		{
			document.getElementById("row"+id).style.display = "";
			document.getElementById("showdetails"+id).innerHTML = "Hide Details";
		}
		else
		{
			document.getElementById("row"+id).style.display = "none";
			document.getElementById("showdetails"+id).innerHTML = "Show Details";
		}
	}

//for updating subcategories for logged in vendors on search_rfps page
function updateSubcategories1(cat_id)
{
	// get the ID of the category whose subcategories we want to display
	selectedCatId = cat_id.options[cat_id.selectedIndex].value;
	// get a reference to the select in which to display them
	subcatOptions = document.forms['searchForm'].elements['subCategoryId'];
	// remove current options from subcatOptions
	for (var ix=subcatOptions.options.length;ix>0;ix--) {
		subcatOptions.options[ix-1] = null;
	}
	// Set first element as "All"
	subcatOptions.options[0] = new Option('All','0');
	// loop through subcat, those that match the selected category are added to subcatOptions
	for (var ix=0;ix<subcat.length;ix++) {
		foo = subcat[ix];
		if (selectedCatId == 0){
			subcatOptions.options[subcatOptions.options.length] = new Option(foo[2],foo[1]);
		}
		else{
		if (foo[0] == selectedCatId) {
			subcatOptions.options[subcatOptions.options.length] = new Option(foo[2],foo[1]);
			}
		}
	}						
	//Check weather selected category has any sub categories
	/*if(selectedCatId != "" && subcatOptions.options.length == 1)
	 {
	        alert("No timeslot available to Trade. Try other Captain!!");
	        cat_id.value = "";
	        return false;
	 }*/
}

//for updating subcategories for vendors on show_rfps page
function updateSubcategories(cat_id)
{
	// get the ID of the category whose subcategories we want to display
	selectedCatId = cat_id.options[cat_id.selectedIndex].value;
	// get a reference to the select in which to display them
	subcatOptions = document.forms['searchForm'].elements['subCategoryId'];
	// remove current options from subcatOptions
	for (var ix=subcatOptions.options.length;ix>0;ix--) {
		subcatOptions.options[ix-1] = null;
	}
	// blank first element
	subcatOptions.options[0] = new Option('Select a SubCategory','0');
	// loop through subcat, those that match the selected category are added to subcatOptions
	for (var ix=0;ix<subcat.length;ix++) {
		foo = subcat[ix];
		if (foo[0] == selectedCatId) {
		subcatOptions.options[subcatOptions.options.length] = new Option(foo[2],foo[1]);
		}
	}						
	//Check weather selected category has any sub categories
	/*if(selectedCatId != "" && subcatOptions.options.length == 1)
	 {
	        alert("No timeslot available to Trade. Try other Captain!!");
	        cat_id.value = "";
	        return false;
	 }*/
}
//function for validating search rfps				
function validateSearchRFPS(formObj)
{
	if(formObj.categoryId.value == 0)
	{
		alert("Please select a category");
		return false;
	}
	if(formObj.subCategoryId.value == 0)
	{
		alert("Please select a Subcategory");
		return false;
	}					
}

function setSessionVar(selectedVal){
	var auth_token = document.getElementById('authenticity_token').value;
	var url = '/account/visitor_type/?selected_val='+selectedVal+'&authenticity_token='+auth_token;
	new Ajax.Request(url, {method: 'post'});
}

//Passing selected search state and city
function passValues(subcat_id){
var visitorType = document.getElementById('accounttype1').checked;
//var state = document.getElementById('state').value;
//var city = document.getElementById('search_city').value;
var targetURL = "";
if(visitorType)
	targetURL = "http://www.projectbidding.com/account/view_company/"+subcat_id;
else
	targetURL = "http://www.projectbidding.com/account/show_rfps/"+subcat_id;
document.location = targetURL;
}

//Search function for left div in view_company module
function searchVendorList(subcat_id){
//var searchString = document.getElementById('search_service1').value;
var state = document.getElementById('state').value;
var city = document.getElementById('search_city').value;
var visitorType = document.getElementById('accounttype1').checked;
/*if(trim(searchString).length > 0){
	targetUrl = "http://www.projectbidding.com/account/search_results/?search_service="+searchString;	
}	
else{*/
	if(visitorType)
		//targetUrl =  "http://localhost:3000/account/view_company/"+subcat_id+"?state="+state+"&city="+city;	
		targetUrl =  "http://www.projectbidding.com/account/view_company/"+subcat_id+"?state="+state+"&city="+city;	
	else
		targetUrl =  "http://www.projectbidding.com/account/show_rfps/"+subcat_id+"?state="+state+"&city="+city;		
//}
document.location = targetUrl;
}
//Header search Validation
function validateSearch(){
var searchString = document.getElementById('search_service');	
if( trim(searchString.value).length == 0 ){
		alert("Search String Cant be Blank");
		searchString.focus();
		return false;
	}
	
}
//Left div search  validation
function validateNarrowSearch(){
var searchString1 = document.getElementById('search_service1').value;
if( trim(searchString1).length == 0 ){
		alert("Search String Cant be Blank");
		document.getElementById('search_service1').focus();
		return false;
	}
else{
		document.location = "http://www.projectbidding.com/account/search_results/?search_service="+searchString1;		
	}
}
function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
//create a variable to store a window object
var popup_window;

//function to open a pop-up window
function open_popup_window(url)
{
	popup_window = window.open(url,'','top=20,left=60,width=800,height=650,status=yes,scrollbars=yes');
}
function validate_pwd()
{
	if(document.getElementById('curr_pass')=="")
	{
		alert("Curr pass cant be blank");
		return false;
	}	
}
function validateAmount()
{       
	var amount = document.getElementById('quotes_amount').value;
        var amountExp = /^[0-9,]*$/
	if(amount=="" && trim(amount).length==0)
	{
		alert("Amount Can't be Blank");
		return false;
	}
    else
	{
		if( !amount.match(amountExp) )
		{
            alert("Invalid bid amount");
            return false;
        }
        else
		{
			var formatted_amount = amount;
			var split_amount_array = new Array()
			split_amount_array = formatted_amount.split(',')
			if(split_amount_array.length > 1)
			{
				formatted_amount = "";
				for(var i=0;i<split_amount_array.length;i++)
				{
					formatted_amount += split_amount_array[i];
				}
			}
			var parsed_amount = (Math.round(formatted_amount * Math.pow(10,0)) / Math.pow(10,0)).toString();
            document.getElementById('quotes_amount').value = parsed_amount;
	        }
         }
}
function enableButton()
{
	var chkbox = document.getElementById('advertisement_banner_amount_active');
	if(chkbox.checked)
	{
		document.uploadForm.advertisement_filename.disabled=false;			
		//document.uploadForm.banner_amount.disabled=false;
	}
	else
	{
		document.uploadForm.advertisement_filename.disabled=true;
		//document.uploadForm.banner_amount.disabled=true;
	}
}
//Email address validation
function echeck(str)
{
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1){
		alert("Invalid Email Address")
		return false
	}
	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr)
	{
		alert("Invalid Email Address")
		return false
	}
	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr)
	{
		alert("Invalid Email Address")
		return false
	}
	if (str.indexOf(at,(lat+1))!=-1){
		alert("Invalid Email Address")
		return false
	}
	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot)
	{
		alert("Invalid Email Address")
		return false
	}
	if (str.indexOf(dot,(lat+2))==-1)
	{
		alert("Invalid Email Address")
		return false
	}	
	if (str.indexOf(" ")!=-1)
	{
		alert("Invalid Email Address")
		return false
	}
	return true					
}

function validate_vendor_setup_form()
{
	var vendor_name = document.getElementById('vendor_profile_vendor_name');
	var email_address = document.getElementById('vendor_profile_email');
	/*var first_name = document.getElementById('user_profile_firstname');
	var last_name = document.getElementById('user_profile_lastname');	
	var address1 = document.getElementById('address_address1');	
	var city = document.getElementById('address_city');
	var zip_code = document.getElementById('address_zipcode');*/
	if(vendor_name.value == "")
	{
		alert("Please enter Vendor Name");
		vendor_name.focus();
		return false;
	}	
	else if(email_address.value == "")
	{
		alert("Please enter Email Address");
		email_address.focus();
		return false;
	}
	else if(email_address.value != "" && echeck(email_address.value)==false)
	{
		email_address.focus()
		return false
	}
	/*else if(first_name.value == "")
	{
		alert("Please enter First Name");
		first_name.focus();
		return false;
	}
	else if(last_name.value == "")
	{
		alert("Please enter Last Name");
		last_name.focus();
		return false;
	}
	else if(address1.value == "")
	{
		alert("Plase enter Address1");
		address1.focus();
		return false;
	}	
	else if(city.value == "")
	{
		alert("Please enter City");
		city.focus();
		return false;
	}
	else if(zip_code.value == "")
	{
		alert("Please enter Zipcode");
		zip_code.focus();
		return false;
	}*/
	else
	{
		var vendor_setup_form = document.getElementById('vendor_setup_form');
		vendor_setup_form.action = "/auction/save_vendor_setup";
		vendor_setup_form.submit();
	}
}

function submit_form(btn,user_profile_id)
{
	alert(user_profile_id);
	
}

function validate_amount()
{
	var amount = document.getElementById('quote_amount');
	var amountExp = /^[0-9,]*[.]?[0-9,]*$/
	var error_message = "";
	document.getElementById('message').innerHTML = error_message;
	/*if (document.getElementById('update'))
			document.getElementById('update').disabled = false;
	if (document.getElementById('create'))
			document.getElementById('create').disabled = false;*/
	if( amount.value == "" )
	{
		error_message = "Please enter bid amount"
		document.getElementById('message').innerHTML = error_message;
		document.getElementById('error_message').value = error_message;
		/*if (document.getElementById('update'))
			document.getElementById('update').disabled = true;
		if (document.getElementById('create'))
			document.getElementById('create').disabled = true;*/
	}
	else
	{
		if( !amount.value.match(amountExp) )
		{
			error_message = "Invalid bid amount";
			document.getElementById('message').innerHTML = error_message;
			document.getElementById('error_message').value = error_message;
			/*if (document.getElementById('update'))
				document.getElementById('update').disabled = true;
			if (document.getElementById('create'))
				document.getElementById('create').disabled = true;*/
		}
		else
		{
			var formatted_amount = amount.value;
			var split_amount_array = new Array()
			split_amount_array = formatted_amount.split(',')
			if(split_amount_array.length > 1)
			{
				formatted_amount = "";
				for(var i=0;i<split_amount_array.length;i++)
				{
					formatted_amount += split_amount_array[i];
				}
			}
			var parsed_amount = (Math.round(formatted_amount * Math.pow(10,0)) / Math.pow(10,0)).toString();			
			document.getElementById('quote_amount').value = parsed_amount;
		}
	}	
}

function hidediv(div_id)
{ 
	document.getElementById(div_id).style.visibility = 'hidden'; 
}

function hidediv(div_id)
{ 
	document.getElementById(div_id).style.visibility = 'hidden'; 
}


function validate_all_state(chk_box,total_states)
{
	for( var state=0; state<total_states; state++ )
	{
		x = document.getElementById("state"+state)
		if( chk_box.checked )
			x.checked = true;
		else
			x.checked = false;
	}
	return true;
}


var rfps = new Array();
function checkAllRFPs()
{

	for (vend=0; vend < rfps.length; vend++)
	{
		var vend_id = rfps[vend];		
		x = document.getElementById("rfp"+vend_id);
		x.checked = true;
	}
	
}
function clearAllRFPs()
{
	for (var vend=0; vend<rfps.length; vend++)
	{
		var vend_id = rfps[vend];
		x = document.getElementById("rfp"+vend_id);
		x.checked = false;		
	}
}
function validateRFP(){
	var rfp_count;
	var checkRPF;
	for (rfp_count=0; rfp_count < rfps.length; rfp_count++)
	{
		var rfp_id = rfps[rfp_count];		
		x = document.getElementById("rfp"+rfp_id);
		if(x.checked == true)
		{
			checkRPF = true;
			break;
		}
		else	
			checkRPF = false;
	}
	if(checkRPF == false)
	{
		alert("Please select at least one RFP.");
		return false;
	}

}
var total_vends = new Array();	
function checkAll(checkAllFlag)
{
	var vendorCount = total_vends.length;
	if(vendorCount > 5 && !checkAllFlag) {
		vendorCount = 5;
		clearAll();
	}
	for (vend=0; vend < vendorCount; vend++)
	{
		var vend_id = total_vends[vend];		
		x = document.getElementById("vendor"+vend_id);
		x.checked = true;
	}
	return true;	
}

function clearAll()
{
	for (var vend=0; vend<total_vends.length; vend++)
	{
		var vend_id = total_vends[vend];
		x = document.getElementById("vendor"+vend_id);
		x.checked = false;		
	}
	return true;	
}
function validateVendors(){
	var vendChecked = false;
	for (var vend=0; vend<total_vends.length; vend++){
		var vend_id = total_vends[vend];		
		if(document.getElementById("vendor"+vend_id).checked){
			vendChecked = true;
			break;
		}
	}
	if(vendChecked)
		return true;
	else{
		alert("Please Select At Least one Vendor for creating RFP");
		return false;
	}
}
function validateVenSelection(idName){
	var chkBox = document.getElementById(idName);
	if(chkBox.checked){
		return true;
	}
	else{
		alert("Please select the Vendor to Create RFP");
		return false;
	}
}

function chk_subcategories(parentNode)
{	
	for (i=0; i< nodes.length; i++) 
	{
		var nodeValues = nodes[i].split("|");		
		if (nodeValues[1] == parentNode.value) 
		{
			if(parentNode.checked)
			{
				document.getElementById("subcat"+nodeValues[0]).checked = true;
			}
			else
			{
				document.getElementById("subcat"+nodeValues[0]).checked = false;
			}
		}
	}
		
}

function chk_category(childNode)
{	
	for(i=0; i< nodes.length; i++)
	{
		var nodeValues = nodes[i].split("|");
		if(nodeValues[3] == childNode.value)
		{
			if(!document.getElementById("cat"+nodeValues[1]).checked)
				document.getElementById("cat"+nodeValues[1]).checked = true;
			
		}
	}	
}

function isChecked(parentNode)
{	
	var checked = false
	for (i=0; i< nodes.length; i++) 
	{
		var nodeValues = nodes[i].split("|");
		if (nodeValues[1] == parentNode) 
		{			
			if(document.getElementById("subcat"+nodeValues[0]).checked)
			{
				checked = true;
				break;
			}
		}
	}	
	return checked;
}


function validate(v,total)
{
	var counter=0;
	for(i=1; i<=total; i++){
	var vendor = "vendor"+i;
	
		var cb=document.getElementById(vendor);
		if (cb.checked)
			counter++;
    }
	if (counter==0){   
		alert("Please select atleast one vendor")
		return false;
	}
	return true;
}

// Arrays for nodes and icons
var nodes			= new Array();
var openNodes	= new Array();
var icons			= new Array(6);
var all_cat_subcat_array = new Array();
var selected_cat_subcat_array = new Array()

// Loads all icons that are used in the tree
function preloadIcons() 
{
	icons[0] = new Image();
	icons[0].src = "/images/plus.gif";
	icons[1] = new Image();
	icons[1].src = "/images/plusbottom.gif";
	icons[2] = new Image();
	icons[2].src = "/images/minus.gif";
	icons[3] = new Image();
	icons[3].src = "/images/minusbottom.gif";
}


// Create the tree
function createTree(arrName, startNode, openNode)
{
	nodes = arrName;
	if (nodes.length > 0)
	{
		preloadIcons();
		if (startNode == null)
			startNode = 0;
		if (openNode != 0 || openNode != null)
			setOpenNodes(openNode);	
		if (startNode !=0) 
		{			
			var nodeValues = nodes[getArrayId(startNode)].split("|");
			document.write("<a href=\"" + nodeValues[3] + "\" onmouseover=\"window.status='" + nodeValues[2] + "';return true;\" onmouseout=\"window.status=' ';return true;\"><img border=0 src=\"/images/folderopen.gif\" align=\"absbottom\" alt=\"\" />" + nodeValues[2] + "</a><br />");
		}	
		var recursedNodes = new Array();		
		addNode(startNode, recursedNodes);
	}
}

// Returns the position of a node in the array
function getArrayId(node)
{
	for (i=0; i<nodes.length; i++)
	{
		var nodeValues = nodes[i].split("|");
		if (nodeValues[0]==node)
			return i;
	}
}

// Puts in array nodes that will be open
function setOpenNodes(openNode)
{
	for (i=0; i<nodes.length; i++)
	{
		var nodeValues = nodes[i].split("|");
		if (nodeValues[0]==openNode)
		{
			openNodes.push(nodeValues[0]);
			setOpenNodes(nodeValues[1]);
		}
	} 
}


// Checks if a node is open
function isNodeOpen(node)
{
	for (i=0; i<openNodes.length; i++)
		if (openNodes[i]==node) 
			return true;
	return false;
}

// Checks if a node has any children
function hasChildNode(parentNode)
{
	for (i=0; i< nodes.length; i++)
	{
		var nodeValues = nodes[i].split("|");
		if (nodeValues[1] == parentNode)
			return true;
	}
	return false;
}

// Checks if a node is the last sibling
function lastSibling (node, parentNode)
{
	var lastChild = 0;
	for (i=0; i< nodes.length; i++)
	{
		var nodeValues = nodes[i].split("|");
		if (nodeValues[1] == parentNode)
			lastChild = nodeValues[0];
	}
	if (lastChild==node)
		return true;
	return false;
}

// Adds a new node to the tree
function addNode(parentNode, recursedNodes)
{	
	for (var i = 0; i < nodes.length; i++)
	{
		var nodeValues = nodes[i].split("|");
		if (nodeValues[1] == parentNode)
		{			
			var ls	= lastSibling(nodeValues[0], nodeValues[1]);
			var hcn	= hasChildNode(nodeValues[0]);
			var ino = isNodeOpen(nodeValues[0]);
			
			// Write out line & empty icons
			for (g=0; g<recursedNodes.length; g++)
			{
				if (recursedNodes[g] == 1)
					document.write("<img border=0 src=\"/images/line.gif\" align=\"absbottom\" alt=\"\" />");
				else
					document.write("<img border=0 src=\"/images/empty.gif\" align=\"absbottom\" alt=\"\" />");
			}
			
			// put in array line & empty icons
			if (ls) 
				recursedNodes.push(0);
			else
				recursedNodes.push(1);
			
			// Write out join icons
			if (hcn)
			{
				if (ls)
				{					
					document.write("<a href=\"javascript: oc(" + nodeValues[0] + ", 1);\"><img border=0 id=\"join" + nodeValues[0] + "\" src=\"/images/");
					 if (ino) 
					 	document.write("minus");
					else
						document.write("plus");
					document.write("bottom.gif\" align=\"absbottom\" alt=\"Open/Close node\" /></a>");
				}
				else
				{					
					document.write("<a href=\"javascript: oc(" + nodeValues[0] + ", 0);\"><img border=0 id=\"join" + nodeValues[0] + "\" src=\"/images/");
					if (ino)
						document.write("minus");
					else
						document.write("plus");
					document.write(".gif\" align=\"absbottom\" alt=\"Open/Close node\" /></a>");
				}
			} 
			else
			{
				if (ls)
					document.write("<img border=0 src=\"/images/joinbottom.gif\" align=\"absbottom\" alt=\"\" />");
				else
					document.write("<img border=0 src=\"/images/join.gif\" align=\"absbottom\" alt=\"\" />");
			}
			
			
			// Write out folder & page icons			
			if (hcn)
			{		
				var checked_flag = "";
				for( var j = 0; j < selected_cat_subcat_array.length; j++ )
				{
					var split_selectedArray = new Array();
					split_selectedArray = selected_cat_subcat_array[j].split("|");				
					if( split_selectedArray[0] == nodeValues[0] )
					{						
						checked_flag = "checked";					
						break;
					}
				}
				document.write("<input type=\"checkbox\" id=\"cat"+nodeValues[0]+"\" name=\"categories["+nodeValues[0]+"]\" value="+nodeValues[0]+" onclick=\"chk_subcategories(this)\" "+checked_flag+" />");					
			} 
			else
			{			
				var checked_flag = "";
				for( var j = 0; j < selected_cat_subcat_array.length; j++ )
				{
					var split_selectedArray = new Array();
					split_selectedArray = selected_cat_subcat_array[j].split("|");								
					if( split_selectedArray[1] == nodeValues[3] && split_selectedArray[0] == nodeValues[1] )
					{						
						checked_flag = "checked";					
						break;
					}
				}		
				document.write("<input type='checkbox' id=\"subcat"+nodeValues[0]+"\" name=\"subcategories["+nodeValues[3]+"]\" value="+nodeValues[3]+" onclick=\"chk_category(this)\" "+checked_flag+" />");				
			}
			
			// Write out node name
			document.write(nodeValues[2]);
			
			// End link
			document.write("</a><br />");
			
			// If node has children write out divs and go deeper
			if (hcn)
			{
				document.write("<div id=\"div" + nodeValues[0] + "\"");
				if (!ino)
					document.write(" style=\"display: none;\"");
				document.write(">");
				addNode(nodeValues[0], recursedNodes);
				document.write("</div>");
			}
			
			// remove last line or empty icon 
			recursedNodes.pop();
		}
	}
}

// Opens or closes a node
function oc(node, bottom)
{
	var theDiv = document.getElementById("div" + node);
	var theJoin	= document.getElementById("join" + node);
	var theIcon = document.getElementById("icon" + node);
	
	if (theDiv.style.display == 'none')
	{
		if (bottom==1)
			theJoin.src = icons[3].src;
		else
			theJoin.src = icons[2].src;
		
		theDiv.style.display = '';
	}
	else
	{
		if (bottom==1)
			theJoin.src = icons[1].src;
		else
			theJoin.src = icons[0].src;		
		theDiv.style.display = 'none';
	}
}

// Push and pop not implemented in IE
if(!Array.prototype.push)
{
	function array_push()
	{
		for(var i=0;i<arguments.length;i++)
			this[this.length]=arguments[i];
		return this.length;
	}
	Array.prototype.push = array_push;
}

if(!Array.prototype.pop)
{
	function array_pop()
	{
		lastElement = this[this.length-1];
		this.length = Math.max(this.length-1,0);
		return lastElement;
	}
	Array.prototype.pop = array_pop;
}


//validation for new advertisement creation

function validateAdForm(){
	//var budgetedAmount = document.getElementById('advertisement_budgeted_amount').value;
	
	var amountExp = /^[0-9,]*[.]?[0-9,]*$/
	if( document.getElementById('advertisement_text').value == '' ){
		alert("Please enter an advertisement text.");
		document.getElementById('advertisement_text').focus();
		return false;
	}
	else if( document.getElementById('advertisement_url').value == '' ){
		alert("Please enter an advertisement URL.");
		document.getElementById('advertisement_url').focus();
		return false;
	}
	else if( document.getElementById('advertisement_number_of_days').value == 0 ){
		alert("Please Select Number of days");
		return false;
	}

	if (document.getElementById('advertisement_filename').value != '' && !/(\.(gif|jpg|jpeg|bmp|png))$/i.test(document.getElementById('advertisement_filename').value)){
		alert("Please attach an image.");
		document.getElementById('advertisement_filename').focus();
		return false;
	}
	/*else if( document.getElementById('advertisement_amount').value == '' ){
		alert("Please enter a cost per click.");
		document.getElementById('advertisement_amount').focus();
		return false;
	}
	else if( document.getElementById('advertisement_amount').value != '' &&  !document.getElementById('advertisement_amount').value.match(amountExp) ){
		alert("Invalid cost per click.");
		document.getElementById('advertisement_amount').focus();
		return false;
	}
	else if( document.getElementById('advertisement_limit').value == '' ){
		alert("Please enter a daily limit.");
		document.getElementById('advertisement_limit').focus();
		return false;
	}
	else if( document.getElementById('advertisement_limit').value != '' &&  !document.getElementById('advertisement_limit').value.match(amountExp) ){
		alert("Invalid daily limit.");
		document.getElementById('advertisement_limit').focus();
		return false;
	}	
	else if( trim(budgetedAmount).length == 0 ){
		alert("Please enter budgeted amount.");
		document.getElementById('advertisement_budgeted_amount').focus();
		return false;
	}	
	else if( budgetedAmount <= 0 ){
		alert("Budgeted Amount must be greater than Zero.");
		document.getElementById('advertisement_budgeted_amount').focus();
		return false;
	}*/
	/*else if(!validateCB('locations',total_states)){
		alert('No checkbox checked in state!');
		return false;
	}*/
	return true;
}
function validateEditAdForm(){

	if( document.getElementById('advertisement_text').value == '' ){
		alert("Please enter an advertisement text.");
		document.getElementById('advertisement_text').focus();
		return false;
	}
	else if( document.getElementById('advertisement_url').value == '' ){
		alert("Please enter an advertisement URL.");
		document.getElementById('advertisement_url').focus();
		return false;
	}
}	
function validatePaymentForm(){
	var fName = document.getElementById('fname').value;
	var lName = document.getElementById('lname').value;
	var credit_card = document.getElementById('payment_card_number').value;
	if(  trim(fName).length == 0 ){
		alert("Please enter your First Name.");
		document.getElementById('fname').focus();
		return false;
	}
	else if(  trim(lName).length == 0 ){
		alert("Please enter your Last Name.");
		document.getElementById('lname').focus();
		return false;
	}
	else if(trim(credit_card).length == 0){
		alert("Please enter your CreditCard Number.");
		document.getElementById('payment_card_number').focus();
		return false;
	}	
	
}
