$(document).ready(function() {
    $("a[rel='cbsingupinfo'],a[rel='cbsingupinfo2']").colorbox({width:"900",height:"530", inline:true, scrolling:false,  href:"#cbsingupinfobox"});
});
    

/*
 * Misc utility functions. For jQuery based util functions, look jquery.utils.js
 */

function preloadImage(imageUrl)
{
    var image = new Image();
    image.src = imageUrl;

    return image;
}

function confirmUrlSubmit(message, url)
{
    if (confirm(message))
    {
        parent.location = url;
        return true;
    }
    else
    {
        return false;
    }
}

function redirect(url)
{
	parent.location = url;
}

function CngBG(obj, nc)
{
    obj.nc = obj.className;
    obj.className = nc;
    obj.onmouseout = function() {
        this.className = this.nc;
    }
}

function textCounter(field, cntfield, maxlimit)
{
    if (field.value.length > maxlimit)
    {
        field.value = field.value.substring(0, maxlimit);
    }
    else
    {
        cntfield.value = maxlimit - field.value.length;
    }
}

// Save scrolling positions
function saveScrollPositions()
{
    var scrOfY = 0;
    if( typeof( window.pageYOffset ) == 'number' )
    {
        //Netscape compliant
        scrOfY = window.pageYOffset;
        scrOfX = window.pageXOffset;
    }
    else if(document.body && (document.body.scrollLeft || document.body.scrollTop))
    {
        //DOM compliant
        scrOfY = document.body.scrollTop;
        scrOfX = document.body.scrollLeft;
    }
    else if(document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop))
    {
        //IE6 standards compliant mode
        scrOfY = document.documentElement.scrollTop;
        scrOfX = document.documentElement.scrollLeft;
    }
        
    $.cookie('mg_posY', scrOfY, {expires : 10, path : '/'});
}

// Maintain scroll position back
function setScrollPositions()
{
    var yPos = $.cookie('mg_posY');
    if (yPos != null)
    {    
        window.scrollBy(0, yPos);
    }
}


function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}

function isModuleFacebook(){
    
    if (MODULE == 'facebook'){
	return true;
    } else {
	return false;
    }
    
}

//To show or hide some div by given id
function toggleDiv(elemId)
{
    var divToToggle = $('#' + elemId);

    if (divToToggle.css('display') == 'block')
    {
        divToToggle.fadeOut(300);
        divToToggle.hide('fast');
    }
    else
    {
        divToToggle.fadeIn('slow');
        divToToggle.css('display', 'block');
    }
    
    return false;
}



// Window Pop Up , Request page
var newwindow;
function poptastic(url)
{
	newwindow=window.open(url,'name','height=700,width=780,left=100, top=40,resizable=yes,scrollbars=yes,toolbar=no,status=no');
	if (window.focus) {newwindow.focus()}
}


// basic funtion to show and hide a div
function showHide(elementid){
    if (document.getElementById(elementid).style.display == 'none'){
        document.getElementById(elementid).style.display = '';
    } else {
        document.getElementById(elementid).style.display = 'none';
    }
}

//Buttons of Support Messages in Dashboard
function valChange(elemId) {
    if (document.getElementById(elemId).value == 'view'){
        document.getElementById(elemId).value='hide';
    }else{
        document.getElementById(elemId).value='view';
    }
}

//expand collapse on Request Section information
function expandCollapse(item) {
obj=document.getElementById(item);
col=document.getElementById("l" + item);
if (col.innerHTML=="[read more]") { obj.style.height="auto"; col.innerHTML="[collapse]"; }
else { obj.style.height="50px"; col.innerHTML="[read more]"; } }


// Function that Loads titles in drop down menu in Request Page
function loadReqTitles(){
    
    //Animals
    var op1=new Array("Animal Rights, Welfare and Services","Wildlife Conservation","Zoos and Aquariums");
    // Art and Culture
    var op2=new Array("Libraries, Historical Societies and Landmark Preservation","Museums","Performing Arts","Public Broadcasting and Media");
    // Education
    var op3=new Array("Universities, Graduate Schools and Technological Institutes","Private Elementary and Secondary Schools","Private Liberal Arts Colleges","Other Educational Programs and Services");
    //Enviromental
    var op4=new Array("Environmental Protection and Conservation","Botanical Gardens, Parks, and Nature Centers");
    //Health
    var op5=new Array("Diseases, Disorders, and Disciplines","Patient and Family Support","Treatment and Prevention Services","Medical Research");
    //Human Services
    var op6=new Array("Children's and Family Services","Youth Development, Shelter, and Crisis Services","Food Banks, Food Pantries and Food Distribution","Multipurpose Human Service Organization","Homeless Services","Social Services");
    //International
    var op7=new Array("Development and Relief Services","International Peace, Security and Affairs","Humanitarian Relief Supplies","Single Country Support Organizations");
    //Public Benefit
    var op8=new Array("Advocacy and Civil Rights","Fundraising Organizations","Research and Public Policy Institutions","Community Foundations","Community and Housing Development");

    var titleOp = document.opform2.req_type.value;
   
    if(titleOp != 0) {
        document.opform2.title.disabled=false;
        var selectedBoxValue=document.opform2.req_type.value;
        var i;
        var j;
        
        removeSelectboxOption();
    
        var titleLengh=eval("op"+selectedBoxValue).length;
   
        for(j=0;j<titleLengh;j++)
        {
            if (j==0){
                document.opform2.title.options[j]=new Option(eval("op"+selectedBoxValue)[j],[j+1],true);
            }
        else if (j>0){
                document.opform2.title.options[j]=new Option(eval("op"+selectedBoxValue)[j],[j+1]);
            }
        }
        
    } else if(titleOp == 0) {
        removeSelectboxOption();
        document.opform2.title.disabled=true;
        removeSelectboxOption();
        document.opform2.title.options[0]=new Option("Choose a Request Category")
    }
    
 }

function removeSelectboxOption()
{
    var i;
    for(i=0;i<document.opform2.title.options.length;i++)
    {
        document.opform2.title.remove(i);
   }
}
 
 
/// Restrict the input of a field
var phone = "()- 0123456789";
var numb = "0123456789.";
var alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ";
function res(t,v){
var w = "";
for (i=0; i < t.value.length; i++) {
x = t.value.charAt(i);
if (v.indexOf(x,0) != -1)
w += x;
}
t.value = w;
}

//



var mgsupport = 'yes';
function enableAdd(){
    if (mgsupport == 'yes')
    {
      $('#mgSupport').html(0.00);
        mgsupport = 'no';
    }
    else
    {
	
        $('#mgSupport').html(1.00);
        mgsupport = 'yes';
    }
}

function valueChange(value){
    var percentage = (eval(value))*.15;
    var support = Number(percentage).toFixed(2);
        
    $('#mgSupport').html(support);
    
}


// return the value of the radio button that is checked
// return an empty string if none are checked, or
// there are no radio buttons
//http://www.somacon.com/p143.php
function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

// set the radio button with the given value as being checked
// do nothing if there are no radio buttons
// if the given value does not exist, all the radio buttons
// are reset to unchecked
function setCheckedValue(radioObj, newValue) {
    
	if(!radioObj) {        
		return;
	}
	var radioLength = radioObj.length;
    
	if(radioLength == undefined) {
		radioObj.checked = (radioObj.value == newValue.toString());
		return;
	}
     

	for(var i = 0; i < radioLength; i++) {
		radioObj[i].checked = false;
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].checked = true;
		}
	}
    
}

//set search engine to initial state
function emptyQuery(queryField) {    
    setAllRadiosUnChecked();     //set all radio buttons unchecked
    $("#" + queryField).val(''); //empty query field
}

function setAllRadiosUnChecked() {
    //var allInputs = $(":radio");    
    $(":radio").attr("checked", false);
}

//set label color by given id
function setLabelColor(className, labelId) {    
    
    $("." + className + " div").removeClass("active_option_label");   
    $("#" + labelId).toggleClass("active_option_label");
}


// funciton to limmit character for text area.
//Use: $('#comment').keyup(function(){ limitChars('comment', 20, 'charlimitinfo'); })


$(document).ready(function() {
    
    ///////////index page
    $("a[rel='mg_presentation']").colorbox({title:'<a href="'+ASSETS_URL+'files/MicroGiving_At-A-Glance.pdf" target="_blank">Download PDF Version</a>'});

    /// Log out
    $("#fblogout").click(function() {
	
	var fbhref = $(this).attr('href');
	
           $.post(CURRENT_URL + 'login/fbout/',{
		'log': 'out'
		} , function(success) {
		    window.location=fbhref;
	    });
	
	return false;
    });



    ///////////////request page
    /*
    $('#req_description2').keyup(function(){
        limitChars('req_description2', 250, 'charlimit_req_description2');
    })
    
    $('#req_description3').keyup(function(){
        limitChars('req_description3', 250, 'charlimit_req_description3');
    })
    
    $('#req_description').keyup(function(){
        limitChars('req_description', 250, 'charlimit_req_description');
    })
    
    $('#req_description4').keyup(function(){
        limitChars('req_description4', 250, 'charlimit_req_description4');
    })
	   
    $('#req_thankyou').keyup(function(){
        limitChars('req_thankyou', 250, 'charlimit_req_thankyou');
    })
    
    $('#req_thankyou2').keyup(function(){
        limitChars('req_thankyou2', 250, 'charlimit_req_thankyou2');
    })
    
    */
		    
    ////////////////////withdraw page
    $('#req_thankyou3').keyup(function(){
        limitChars('req_thankyou3', 250, 'charlimit_req_thankyou3');
    })
    
    $('#req_thankyou4').keyup(function(){
        limitChars('req_thankyou4', 250, 'charlimit_req_thankyou4');
    })
	
    $('#req_thankyou5').keyup(function(){
        limitChars('req_thankyou5', 250, 'charlimit_req_thankyou5');
    })
    
});

function limitChars(textid, limit, infodiv)
{
	var text = $('#'+textid).val();	
	var textlength = text.length;
	if(textlength > limit)
	{
		$('#' + infodiv).html('You cannot write more then '+limit+' characters!');
		$('#'+textid).val(text.substr(0,limit));
		return false;
	}
	else
	{
		$('#' + infodiv).html('You have '+ (limit - textlength) +' characters left.');
		return true;
	}
}


//To show or hide some HTML object by given id and change link
function toggleDivLink(elemId, linkId)
{
    var divToToggle  = $('#' + elemId);
    var linkToToggle = $('#' + linkId);

    if (divToToggle.css('display') == 'block')
    {
        divToToggle.fadeOut(100);
        divToToggle.hide("fast");
        linkToToggle.html("view more");
    }
    else
    {
        divToToggle.fadeIn("slow");
        divToToggle.css('display', 'block');
        linkToToggle.html("view less");
    }

    return false;

} //function toggleDivLink

//** Smooth Navigational Menu- By Dynamic Drive DHTML code library: http://www.dynamicdrive.com
//** Script Download/ instructions page: http://www.dynamicdrive.com/dynamicindex1/ddlevelsmenu/
//** Menu created: Nov 12, 2008

//** Dec 12th, 08" (v1.01): Fixed Shadow issue when multiple LIs within the same UL (level) contain sub menus: http://www.dynamicdrive.com/forums/showthread.php?t=39177&highlight=smooth

//** Feb 11th, 09" (v1.02): The currently active main menu item (LI A) now gets a CSS class of ".selected", including sub menu items.

//** May 1st, 09" (v1.3):
//** 1) Now supports vertical (side bar) menu mode- set "orientation" to 'v'
//** 2) In IE6, shadows are now always disabled

//** July 27th, 09" (v1.31): Fixed bug so shadows can be disabled if desired.


var ddsmoothmenu={

//Specify full URL to down and right arrow images (23 is padding-right added to top level LIs with drop downs):
arrowimages: {down:['downarrowclass', ASSETS_IMAGES_URL+'down.gif', 23], right:['rightarrowclass', 'right.gif']},

transition: {overtime:300, outtime:300}, //duration of slide in/ out animation, in milliseconds
shadow: {enable:false, offsetx:5, offsety:5},

///////Stop configuring beyond here///////////////////////////

detectwebkit: navigator.userAgent.toLowerCase().indexOf("applewebkit")!=-1, //detect WebKit browsers (Safari, Chrome etc)
detectie6: document.all && !window.XMLHttpRequest,

getajaxmenu:function($, setting){ //function to fetch external page containing the panel DIVs
	var $menucontainer=$('#'+setting.contentsource[0]) //reference empty div on page that will hold menu
	$menucontainer.html("Loading Menu...")
	$.ajax({
		url: setting.contentsource[1], //path to external menu file
		async: true,
		error:function(ajaxrequest){
			$menucontainer.html('Error fetching content. Server Response: '+ajaxrequest.responseText)
		},
		success:function(content){
			$menucontainer.html(content)
			ddsmoothmenu.buildmenu($, setting)
		}
	})
},


buildmenu:function($, setting){
	var smoothmenu=ddsmoothmenu
	var $mainmenu=$("#"+setting.mainmenuid+">ul") //reference main menu UL
	$mainmenu.parent().get(0).className=setting.classname || "ddsmoothmenu"
	var $headers=$mainmenu.find("ul").parent()
	$headers.hover(
		function(e){
			$(this).children('a:eq(0)').addClass('selected')
		},
		function(e){
			$(this).children('a:eq(0)').removeClass('selected')
		}
	)
	$headers.each(function(i){ //loop through each LI header
		var $curobj=$(this).css({zIndex: 100-i}) //reference current LI header
		var $subul=$(this).find('ul:eq(0)').css({display:'block'})
		this._dimensions={w:this.offsetWidth, h:this.offsetHeight, subulw:$subul.outerWidth(), subulh:$subul.outerHeight()}
		this.istopheader=$curobj.parents("ul").length==1? true : false //is top level header?
		$subul.css({top:this.istopheader && setting.orientation!='v'? this._dimensions.h+"px" : 0})
		$curobj.children("a:eq(0)").css(this.istopheader? {paddingRight: smoothmenu.arrowimages.down[2]} : {}).append( //add arrow images
			'<img src="'+ (this.istopheader && setting.orientation!='v'? smoothmenu.arrowimages.down[1] : smoothmenu.arrowimages.right[1])
			+'" class="' + (this.istopheader && setting.orientation!='v'? smoothmenu.arrowimages.down[0] : smoothmenu.arrowimages.right[0])
			+ '" style="border:0;" />'
		)
		if (smoothmenu.shadow.enable){
			this._shadowoffset={x:(this.istopheader?$subul.offset().left+smoothmenu.shadow.offsetx : this._dimensions.w), y:(this.istopheader? $subul.offset().top+smoothmenu.shadow.offsety : $curobj.position().top)} //store this shadow's offsets
			if (this.istopheader)
				$parentshadow=$(document.body)
			else{
				var $parentLi=$curobj.parents("li:eq(0)")
				$parentshadow=$parentLi.get(0).$shadow
			}
			this.$shadow=$('<div class="ddshadow'+(this.istopheader? ' toplevelshadow' : '')+'"></div>').prependTo($parentshadow).css({left:this._shadowoffset.x+'px', top:this._shadowoffset.y+'px'})  //insert shadow DIV and set it to parent node for the next shadow div
		}
		$curobj.hover(
			function(e){
				var $targetul=$(this).children("ul:eq(0)")
				this._offsets={left:$(this).offset().left, top:$(this).offset().top}
				var menuleft=this.istopheader && setting.orientation!='v'? 0 : this._dimensions.w
				menuleft=(this._offsets.left+menuleft+this._dimensions.subulw>$(window).width())? (this.istopheader && setting.orientation!='v'? -this._dimensions.subulw+this._dimensions.w : -this._dimensions.w) : menuleft //calculate this sub menu's offsets from its parent
				if ($targetul.queue().length<=1){ //if 1 or less queued animations
					$targetul.css({left:menuleft+"px", width:this._dimensions.subulw+'px'}).animate({height:'show',opacity:'show'}, ddsmoothmenu.transition.overtime)
					if (smoothmenu.shadow.enable){
						var shadowleft=this.istopheader? $targetul.offset().left+ddsmoothmenu.shadow.offsetx : menuleft
						var shadowtop=this.istopheader?$targetul.offset().top+smoothmenu.shadow.offsety : this._shadowoffset.y
						if (!this.istopheader && ddsmoothmenu.detectwebkit){ //in WebKit browsers, restore shadow's opacity to full
							this.$shadow.css({opacity:1})
						}
						this.$shadow.css({overflow:'', width:this._dimensions.subulw+'px', left:shadowleft+'px', top:shadowtop+'px'}).animate({height:this._dimensions.subulh+'px'}, ddsmoothmenu.transition.overtime)
					}
				}
			},
			function(e){
				var $targetul=$(this).children("ul:eq(0)")
				$targetul.animate({height:'hide', opacity:'hide'}, ddsmoothmenu.transition.outtime)
				if (smoothmenu.shadow.enable){
					if (ddsmoothmenu.detectwebkit){ //in WebKit browsers, set first child shadow's opacity to 0, as "overflow:hidden" doesn't work in them
						this.$shadow.children('div:eq(0)').css({opacity:0})
					}
					this.$shadow.css({overflow:'hidden'}).animate({height:0}, ddsmoothmenu.transition.outtime)
				}
			}
		) //end hover
	}) //end $headers.each()
	$mainmenu.find("ul").css({display:'none', visibility:'visible'})
},

init:function(setting){
	if (typeof setting.customtheme=="object" && setting.customtheme.length==2){ //override default menu colors (default/hover) with custom set?
		var mainmenuid='#'+setting.mainmenuid
		var mainselector=(setting.orientation=="v")? mainmenuid : mainmenuid+', '+mainmenuid
		document.write('<style type="text/css">\n'
			+mainselector+' ul li a {background:'+setting.customtheme[0]+';}\n'
			+mainmenuid+' ul li a:hover {background:'+setting.customtheme[1]+';}\n'
		+'</style>')
	}
	this.shadow.enable=(document.all && !window.XMLHttpRequest)? false : this.shadow.enable //in IE6, always disable shadow
	jQuery(document).ready(function($){ //ajax menu?
		if (typeof setting.contentsource=="object"){ //if external ajax menu
			ddsmoothmenu.getajaxmenu($, setting)
		}
		else{ //else if markup menu
			ddsmoothmenu.buildmenu($, setting)
		}
	})
}

} //end ddsmoothmenu variable




// Place example text inside an input
//
function switchText()
{
	if ($(this).val() == $(this).attr('title'))
		$(this).val('').removeClass('exampleText');
	else if ($.trim($(this).val()) == '')
		$(this).addClass('exampleText').val($(this).attr('title'));
}

