$(document).ready(function(){
        //FORMS
        $('.submit-ajax')
                .click(function() {
					//if(!$(this).hasClass('button-loading'))
					//{
						//$(this).addClass('button-loading');
						
						$('.process').hide();
						$('#processdiv').show();
						
						$(this).Ajax_Form_Submit();
					//}
					
					return false;
				});
                
        $('.submit-field')
                .keypress( function(event) {
                        if (event.keyCode == 13)
                        {
                                $(this).Ajax_Form_Submit();
                                return false;
                        }
                });
        
        $('.blink')
                .focus( function(){
                        if( $( this ).attr('value') == $(this).attr('title') ) {
                                $( this ).attr({ 'value': '' });
                                $( this ).addClass( 'field-writing' );
                        }
                })
                .blur( function(){
                        if( $( this ).attr('value') == '' ) {
                                $( this ).attr({ 'value': $(this).attr('title') });
                                $( this ).removeClass( 'field-writing' );
                        }
                                
                });


        $('.select-text')
                .live('focus',function() {
                        $(this).select();
                })
                .live('click',function() {
                        $(this).select();
                });
                
        $('table tr')
                .live('mouseover',function() {
                        $(this).addClass('hover');
                })
                .live('mouseout',function() {
                        $(this).removeClass('hover');
                });
        $('.comments .comment')
                .live('mouseover',function() {
                        $(this).addClass('hovered-comment');
                })
                .live('mouseout',function() {
                        $(this).removeClass('hovered-comment');
                });
                
        $('.chart-expanders .expander')
                .live('mouseover',function() {
                        $(this).addClass('expander-hover');
                })
                .live('mouseout',function() {
                        $(this).removeClass('expander-hover');
                });
                
        $('.chart-expanders .expander')
                .live('click', function() {
                        $(this).toggleClass('expander-cselected');
                        $(this).find('.content:eq(0)').toggle();
                });
                
        
        $('.main-table tr.clicker')
                .live('click', function(e) {
                
                        //if($(e).parent().is('a'))
                        //        return true;
                        
                        $(this).toggleClass('cselected');
                        $(this).find('tr.info:eq(0)').toggle();
                });
        
        $('#sup-nav ul li#another-fund')
                .click(function() {
                        $(this).find('a:eq(0)').toggleClass('clicked');
                        $(this).find('.dropdown').toggle('normal');
                        return true;
                }).hover(function() {
                }, function() {
                        $(this).find('a:eq(0)').removeClass('clicked');
                        $(this).find('.dropdown').hide('normal');
                });
                
        $('.simple-form .checker')
                .click(function() {
                        $('.simple-form .checker').attr({'title': ''});
                        $('.simple-form .checker').removeClass('checked-checker');
                        $('.simple-form .checkers .checker-content').hide();
                        
                        $(this).toggleClass('checked-checker');
                        
                        if ($(this).hasClass('checked-checker')) {
                                $(this).attr({'title': 'checked'});
                                $(this).parent().find('.checker-content').show();
                        } else {
                                $(this).attr({'title': ''});
                                $(this).parent().find('.checker-content').hide();
                        }
                });
                
        $('.simple-form .row')
                .click(function() {
                        $('.simple-form .row').removeClass('selected-row');
                        $(this).toggleClass('selected-row');
                });
                
        $('.simple-form .row .field')
                .focus(function() {
                        $('.simple-form .row').removeClass('selected-row');
                        $(this).parents('.row:eq(0)').addClass('selected-row');
                });
        
        //DONATIONS MANAGER -----
        if($('#fm-donations').length >0)
        {
		fmdonations(0,'fm',$('#fm-donations'));
        }
	
        if($('#all-donations').length >0)
        {
		fmdonations(0,'all',$('#all-donations'));
	}
                
                
         //Updates MANAGER ----
        if($('#all-updates').length >0)
        {
		fmupdates(0,'all',$('#all-updates'));
	}
	
	$('.comments .comment .allupdatesclose').live('click', function() {
        
                var html = $.ajax(
                {url: 'index.php?route=controls/deleteupdate&cm='+parseInt($(this).attr('id'))+'&f='+$('#fund-id').val()+'&ci=0&m=fm', 
                async: false, 
                type:"GET"}).responseText;
        
                fmupdates(0,'all',$('#all-updates'));
                
                return false;
        });
	 
	
       
	//COMMENTS MANAGER ----
        if($('#fm-comments').length >0)
	{
		fmcomments(0,'fm',$('#fm-comments'));
        }
	
        if($('#all-comments').length >0)
        {
		fmcomments(0,'all',$('#all-comments'));
        }
	
        $('.comments .comment .fmclose').live('click', function() {
        
                var html = $.ajax(
                {url: 'index.php?route=controls/deletecomment&cm='+parseInt($(this).attr('id'))+'&f='+$('#fund-id').val()+'&ci=0&m=fm', 
                async: false, 
                type:"GET"}).responseText;
        
                fmcomments(0,'fm',$('#fm-comments'));
                
                return false;
        });
        $('.comments .comment .allclose').live('click', function() {
        
                var html = $.ajax(
                {url: 'index.php?route=controls/deletecomment&cm='+parseInt($(this).attr('id'))+'&f='+$('#fund-id').val()+'&ci=0&m=fm', 
                async: false, 
                type:"GET"}).responseText;
        
                fmcomments(0,'all',$('#all-comments'));
                
                return false;
        });
        
        //ORG USERS---------
        if($('#org-users').length >0)
        {
		orgusers(0,'all',$('#org-users'));
	}
	
        //ORG FUNDS---------
        if($('#manage-funds').length >0)
        {
		orgfunds(0,'all',$('#manage-funds'));
        }
	
        //SYSTEM MESSAGE
        $('#system-message .close')
                .live('click', function() {
                        $('#system-message').remove();        
                        return false;
                });
        
        $('#system-message.fade').fadeTo(5000,1).animate({height: "0px", opacity: 0}, 400 );        
        
        
        //embed
        if($('.embed-select').length>0)
		{
			var embedCode = $('.embed-select').val().replace(/#/, $('#embedSize').val());
			$('.embed-text').val(embedCode);
			
			var share=$(".embed-select option:selected").attr('share');
			//alert(share);
			$('.embed-share').html(share);
			
			var url =$(".embed-select option:selected").attr('url');
			$('#editurl').attr('href','index.php?route=edit&url='+url);
		}
        $('.embed-select')
                .change(function() {
						var embedCode = $('.embed-select').val().replace(/#/, $('#embedSize').val());
                        $('.embed-text').val(embedCode);
						$('.embed-share').html($(".embed-select option:selected").attr('share'));
						$('#editurl').attr('href','index.php?route=edit&url='+$(".embed-select option:selected").attr('url'));
		                return false;
                });
		$('.embed-radio')
				.live('click', function() {
					$('.embed-radio').removeClass('selected').addClass('deselected');
					$(this).removeClass('deselected').addClass('selected');
					
					$('#embedSize').val($(this).attr('title'));
					
					var embedCode = $('.embed-select').val().replace(/#/, $('#embedSize').val());
                    $('.embed-text').val(embedCode);
                        
					return false;
				});
				
                
                
        $('.print-csv')
                .live('click', function() {
                        //
                        // Defaults (don't leave it to the browser)  
                        var defaultParams = {  
                                "width":       "800",   // Window width  
                                "height":      "600",   // Window height  
                                "directories": "no",    // Show directories/Links bar?  
                                "location":    "no",    // Show location/address bar?  
                                "resizeable":  "yes",   // Make the window resizable?  
                                "menubar":     "no",    // Show the menu bar?  
                                "toolbar":     "no",    // Show the tool (Back button etc.) bar?  
                                "scrollbars":  "yes",   // Show scrollbars?  
                                "status":      "no"     // Show the status bar?  
                                };  
                                
                        var w = window.open("index.php?route=export/printcsv", "printable", defaultParams);  
                        w.print();
                        return false;
                });
        $('.print-emails')
                .live('click', function() {
                        //
                        // Defaults (don't leave it to the browser)  
                        var defaultParams = {  
                                "width":       "800",   // Window width  
                                "height":      "600",   // Window height  
                                "directories": "no",    // Show directories/Links bar?  
                                "location":    "no",    // Show location/address bar?  
                                "resizeable":  "yes",   // Make the window resizable?  
                                "menubar":     "no",    // Show the menu bar?  
                                "toolbar":     "no",    // Show the tool (Back button etc.) bar?  
                                "scrollbars":  "yes",   // Show scrollbars?  
                                "status":      "no"     // Show the status bar?  
                                };  
                                
                        var w = window.open("index.php?route=export/printemails", "printable", defaultParams);  
                        return false;
                });
        
        //SHARE
        $('#dash-invite')
                .live('click', function() {
                        if($('#invite-select').val()!="")
                        {
                                window.location="index.php?route=fundwizard/wizard4&url="+$('#invite-select').val();
                        }
                        return false;
                });
        
        //ADD USER
        $('.perms')
                .live('click', function() {
                        $("#perms-full").val(parseInt($(this).attr('id')));
                        return false;
                });
        $('#adduser-cancel')
                .live('click', function() {
                        window.location="index.php?route=dashboard/users";
                        return false;
                });
                
        //PAGING
        $('.next-link')
                .live('click', function() {
                        $("#"+$('#content-div-id').val()).load($(this).attr('href'));
                        return false;
                });
        $('.back-link')
                .live('click', function() {
                        $("#"+$('#content-div-id').val()).load($(this).attr('href'));
                        return false;
                });
        
        //Fundmanager
        $('.pplb')
                .live('click', function() {
                        showPaypal();
                        return false;
                });
		
	 $('.update-button')
                .live('click', function() {
                      
			var t = $('.update-text').val();
			
			if(t.length < 3 || t==$('.update-text').attr('title'))
			{
				//alert('Please enter an Update to your fund.');
				$('.update-title').eq(0).html('Enter text first!');
				
				return;
			}
			
			var html = $.ajax({
			url:'index.php?route=fundmanager/postupdate', 
			async:false, 
			type:"POST", 
			data:"Updates[text]="+valueClean(t)+"&Updates[fund_id]="+$('.update-fund-id').val()+"&Social[fb]="+$('.update-post-fb').is(':checked')
			}).responseText;
			
			$('.update-text').val($('.update-text').attr('title'));
			$('.update-title').toggle();
			
			fmupdates(0,'all',$('#all-updates'));
			
			$('.update').append(html);
			
			
                        return false;
                });
		
        
        //SIGN UP
        $('.user-name')
                .blur(function() {
                        var text= cleanUrl($("#first-name").val()+""+$("#last-name").val());
                        $('.url-source').each(function(){$(this).val(text);});
                        $('.url-sync').each(function(){$(this).html(text);});
                });
        $('.org-name')
                .blur(function() {
                        var text= cleanUrl($(this).val());
                        
                        $('.url-source').each(function(){$(this).val(text);});
                        $('.url-sync').each(function(){$(this).html(text);});
                });
        $('.url-source')
                .live('keyup', function() {
                        var text= cleanUrl($(this).val());
                        $('.url-sync').each(function(){$(this).html(text);});
                });
                
        $('.paypal-what-is-this')
                .live('click', function() {
                        window.open( "https://www.paypal.com/us/cgi-bin/webscr?cmd=p/acc/cvv_info_pop-outside", "myWindow", 
                        "status = 1, height = 400, width = 450, resizable = 1" );
                        
                        return false;
        });
				
		 $('.signup-paychoice')
                .change(function() {
                    if($(this).val()=="paysimple")
						$('#paysimplediv').show();
					
					return false;
                        
                });
       
				$('.countryselect').change(function() {
		countryselectstate();
	});
	
	function countryselectstate()
	{
		if($('.countryselect').val()!='US')
		{
			$('.state-field').hide();
			//$('.state-text-field').show();
			$('.region-tip').text('Please enter the city and postal code of your billing address.');
			$('#lbl_location').text('City & Postal');
		}
		else
		{
			$('.state-field').show();
			//$('.state-text-field').hide();
			$('.region-tip').text('Please enter the city, state and zip code of your billing address.');
			$('#lbl_location').text('City, State, Zip');
		}
	}
	
	countryselectstate();
	
			
                
        //Wizard
        $('input.auto-upload')
                .change(function() {
                        
                        $('form').submit();
                });
        $('#payment-select')
                .change(function() {
                        $('.payment-content').hide();
                        $('.'+$(this).val()+'-content').show();
                        return false;
                        
                });
        if($('#payment-select').length>0)
        {
                $('.payment-content').hide();
                $('.'+$('#payment-select').val()+'-content').show();
        }
                
        $('.dashboard-button')
                .click(function() {
                        top.location="index.php?route=dashboard";
                });
        
        $('.contact-select')
                .click(function() {
                        $('.payment-content').hide();
                        $('.other-content').show();
                        $("#payment-select").val("other");
                        
                        return false;
                });
                
                
        //homepage
        $('.play-button')
                .click(function() {
                                $('#blackbox').show();
                                $('#swfpopup').show();
                                return false;
                        });
        
        //New fund wizard
         $('.fund-name')
                .blur(function() {
                        var text= cleanUrl($("#fundname").val());
                        $('.url-source').each(function(){$(this).val(text);});
                        $('.url-sync').each(function(){$(this).html(text);});
                });
       if($('#templateid').length>0)
        {
                $('.swatch').removeClass('selected-swatch');
                $('#'+$('#templateid').val()+'_color').addClass('selected-swatch');
                
                $('#thumbnailarea').removeClass().addClass('thumb').addClass($('#'+$('#templateid').val()+'_color').attr('title'));        
        }
        
        $('.advanced-toggle')
                .click(function() {
                        $('#advanced').slideToggle();
                        if($(this).html()=='Hide advanced settings')
                        {
                                $(this).html('Show advanced settings');
                        }
                        else
                        {
                                $(this).html('Hide advanced settings');
                        }
                        return false;
                });
        
        $('.swatch')
                .click(function() {
                        $('.swatch').removeClass('selected-swatch');
                        $(this).addClass('selected-swatch');
                        
                        $('#templateid').val(parseInt($(this).attr('id')));
                        
                        $('#thumbnailarea').removeClass().addClass('thumb').addClass($(this).attr('title'));
                        
                        $(this).parents('.row').click();
                        return false;
                });
        
        $('.settings_radio .radio-on')
                .click(function() {
                        $(this).addClass('on').addClass('selected').removeClass('deselected');
                        $('.radio-off',$(this).parent()).removeClass('off').removeClass('selected').addClass('deselected');
                        $('input',$(this).parent()).val(1);
                        return true;
                });
         $('.settings_radio .radio-ac')
                .click(function() {
                        if($(this).hasClass('radio-on'))
				$('.radio-ac-setting').show();
			else
				$('.radio-ac-setting').hide();
                        return true;
                });
        
        $('.settings_radio .radio-off')
                .click(function() {
                        $(this).addClass('off').addClass('selected').removeClass('deselected');
                        $('.radio-on',$(this).parent()).removeClass('on').removeClass('selected').addClass('deselected');
                        $('input',$(this).parent()).val(0);
                        return true;
                });
        $('.preview-link-2')
                .click(function() {
                        
                        var url = $('#previewurl').val();
                        
                        url+="?p=1&t="+$('#templateid').val();
                        url+="&h="+$('#headline').val();
                        url+="&d=1";
                        
                        window.open(url);
                        
                        
                        return false;
                });
        $('.preview-link-3')
                .click(function() {
                        
                        var url = $('#previewurl').val();
                        
                        url+="?p=1";
                        url+="&m="+$('#gmeter').val();
                        url+="&b="+$('#balance').val();
                        url+="&l="+$('#glist').val();
                        url+="&rd="+$('#donations').val();
                        url+="&o="+$('#orginfo').val();
                        
                        
                        window.open(url);
                        
                        
                        return false;
                });
        $('.preview-link-all')
                .click(function() {
                        
                        var url = $('#previewurl').val();
                        
                        url+="?p=1";
                        url+="&t="+$('#templateid').val();
                        url+="&h="+$('#headline').val();
                        url+="&m="+$('#gmeter').val();
                        url+="&b="+$('#balance').val();
                        url+="&l="+$('#glist').val();
                        url+="&rd="+$('#donations').val();
                        url+="&o="+$('#orginfo').val();
                        
                        
                        window.open(url);
                        
                        
                        return false;
                });
                
	$('.close-paypal-video')
	.click(function() {
		$('#video').html('');
		$('#light').hide();
		$('#fade').hide();

		return false;
	});
	$('.open-paypal-video')
		.click(function() {
			$('#video').flash(
		        { 
		          src: 'http://www.createafund.com/flv/link_pay_pal.swf',
		          width: 720,
		          height: 522,
		          flashvars: { bgcolor: '#333' }
		        },
		        { version: 8 }
		    );
		    
			$('#light').show();
			$('#fade').show();

			return false;
		});
	
	$('.fundmanager-button')
		.click(function() {
				window.location=$(this).parent().attr('href');
		});
		
	
        
});
function cleanUrl(text)
{
        text=""+text;
        return text.replace(/[^a-z^A-Z^0-9]/gi,"");
}
function orgusers(i,mode,obj)
{
        obj.load( 'index.php?route=controls/orgusers&ci='+i+'&m='+mode);
}
function orgfunds(i,mode,obj)
{
        obj.load( 'index.php?route=controls/managefunds&ci='+i+'&m='+mode);
}
function fmdonations(i,mode,obj)
{
        obj.load( 'index.php?route=controls/fmdonations&url='+$('#fund-id').val()+'&ci='+i+'&m='+mode);
}
function fmcomments(i,mode,obj)
{
        obj.load( 'index.php?route=controls/fmcomments&url='+$('#fund-id').val()+'&ci='+i+'&m='+mode);
        
}
function fmupdates(i,mode,obj)
{
        obj.load( 'index.php?route=controls/fmupdates&url='+$('#fund-id').val()+'&ci='+i+'&m='+mode);
        
}

function ValidateAddUser()
{
        if(($('#Users-firstname').val() == $('#Users-firstname').attr('title')) || ($('#Users-firstname').val() == ""))
        {
                $('#page-title').html("<strong class='error'>Oops</strong> please enter a valid first name.");
                return false;
        }
        if(($('#Users-lastname').val() == $('#Users-lastname').attr('title')) || ($('#Users-lastname').val() == ""))
        {
                $('#page-title').html("<strong class='error'>Oops</strong> please enter a valid last name.");
                return false;
        }
        if(!isValidEmail($('#Users-email').val()))
        {
                $('#page-title').html("<strong class='error'>Oops</strong> please enter a valid email.");
                return false;
        }
        
        return true;
}

function isValidEmail(str) 
{
   return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
}

//HEADER ----------------
function showRequestPayment()
{
        $('#lbIframe').attr('src',"index.php?route=paypal/payment");
        $('#light').show();
        $('#fade').show();
}
function showPaypal()
{
        $('#lbIframe').attr('src',"index.php?route=paypal/video");
        $('#light').show();
        $('#fade').show();
}

function FacebookLogin(u,t,e)
{
        if(e=='true')
        {
                var defaultParams = {  
                                "directories": "yes",    // Show directories/Links bar?  
                                "location":    "yes",    // Show location/address bar?  
                                "resizeable":  "yes",   // Make the window resizable?  
                                "menubar":     "yes",    // Show the menu bar?  
                                "toolbar":     "yes",    // Show the tool (Back button etc.) bar?  
                                "scrollbars":  "yes",   // Show scrollbars?  
                                "status":      "yes"     // Show the status bar?  
                                };  
                alert('test');
                
                var w = window.open('index.php?route=share/facebookconnect&url='+u+'&embed=1', "name", defaultParams);  
                
                return;
        }
        else if(t)
                window.location='index.php?route=share/facebookconnect&url='+u+'&t='+t;
        else
                window.location='index.php?route=share/facebookconnect&url='+u;        
}

jQuery.fn.Ajax_Form_Error = function(err) {}; //place holder
jQuery.fn.Ajax_Form_Submit = function() 
{
		//$('.submit-ajax').addClass('button-loading').removeClass('submit-ajax');
        var dataStr="";
        
        $('form input').each(function() 
        {
        
        	if(($(this).is(':checkbox') && $(this).is(':checked'))||(!$(this).is(':checkbox')))
                dataStr += $(this).attr('name')+"="+valueClean($(this).val())+"&";
        });
        
        $('form textarea').each(function() 
        {
                dataStr += $(this).attr('name')+"="+valueClean($(this).val())+"&";
        });
        
        $('form select').each(function() 
        {
                dataStr += $(this).attr('name')+"="+valueClean($(this).val())+"&";
        });
        //alert($('form').attr('action'));
        
        var html = $.ajax({
                url:$('form').attr('action'), 
                async:false, 
                type:"POST", 
                data:dataStr
                }).responseText;
        
        
        if(html.substring(0,2)=="OK")
        {
            window.location=html.substring(3);
        }
        else
        {
            $(this).Ajax_Form_Error(html);
	        $('.process').show();
	        $('#processdiv').hide();
	       	//$('.button-loading').addClass('submit-ajax').removeClass('button-loading');
        }        
        
        
        return false;
};
jQuery.fn.Ajax_Form_Alert = function(titleerror,title,errorclass,errormsg,lbl) 
{
        $(titleerror)
                .show()
                .addClass(errorclass)
                .html(errormsg);
                                        
        $(title).hide();
        
        $(lbl).addClass(errorclass);
};
function valueClean(val) 
{
	 return val.replace(/&/gi,"#amp;");
}

$.getDocHeight = function(){
	//document.write ($(document).height()+","+$(window).height()+","+document.documentElement.clientHeight);
	
	if($(document).height()>0)
		return $(document).height();
		
	return Math.max(
		$(document).height(),
		$(window).height(),
		/* For opera: */
		document.documentElement.clientHeight
	);
};

