
function close_modal(){
	$("#modalClose").click();
}
var Base64 = {
 
	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
 
	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = Base64._utf8_encode(input);
 
		while (i < input.length) {
 
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
 
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
 
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
 
			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
 
		}
 
		return output;
	},
 
	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
 
		while (i < input.length) {
 
			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));
 
			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;
 
			output = output + String.fromCharCode(chr1);
 
			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}
 
		}
 
		output = Base64._utf8_decode(output);
 
		return output;
 
	},
 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
 
}

function createModal(){
	if ( $("#myEmail").val() != "" && $("#myVote").val() != "" )
	{
		if ($("#checkBox:checked").val()){
			var check = 1;
		}
		else{
			var check = 0;
		}
		var params = {
			email: Base64.encode($("#myEmail").val()),
			nomination: Base64.encode($("#myVote").val()),
			check: check
		};
		
		var url = "/includes/thickbox_content?" + $.param(params);

		$("#colorbox_dummy").colorbox({
			iframe: true, 
			href: url,
			fixedWidth: 375,
			open: true
		});

		// allow transparent iframe in IE
		if($.browser.msie){
			$('#modalLoadedContent iframe').each(function(index) {
				$(this).attr('scrolling', 'no').attr('allowtransparency', 'true').clone(true).insertAfter(this);
				$('#modalLoadedContent iframe:first').remove();
			});
		}
	}
}

function is_email(s){
        var reg = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        return reg.test(s);
}

function validate(formData, jqForm, options){
        $(jqForm).addClass('active');
        $('body').addClass('wait');

        var regemail = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        var errors = '';

        for (var i=0; i < formData.length; i++){
                if(!formData[i].value){
                        if(formData[i].name == 'name'){
                                errors = errors + '<li>The Name field is required</li>';
                        }

                        if(formData[i].name == 'email'){
                                errors = errors + '<li>The Email field is required</li>';
                        }

                        if(formData[i].name == 'comment'){
                                errors = errors + '<li>The Comment field is required</li>';
                        }
                }
                else if(formData[i].name == 'email' && !is_email(formData[i].value)){
                        errors = errors + '<li>A valid Email is required</li>';
                }
        }

        if(errors.length > 0){
                $('form.active').removeClass('active').prev('.messages').html('<ul class="errors">' + errors + '</ul>').fadeIn(300);
                //$('form.active').removeClass('active').prev('.messages').css('display', 'block').hide().html('<ul class="errors">' + errors + '</ul>').fadeIn(300);
                $(jqForm).removeClass('active');
                $('body').removeClass('wait');

                return false;
        }
        else{
                return true;
        }
}

function commentResponse(responseText, statusText){
        if(responseText.search('<div id="bodyCopy" class="contactForm">') != -1){
                errors = responseText.substring(responseText.indexOf('<div id="bodyCopy" class="contactForm">') + '<div id="bodyCopy" class="contactForm">'.length);
                errors = errors.substring(0, errors.indexOf('</div>'));
                errors = errors.substring(errors.indexOf('<ul>') + '<ul>'.length);
                errors = errors.substring(0, errors.indexOf('</ul>'));

                if(errors != null){
                        if(errors.length > 0){
                                $('form.active').removeClass('active').prev('.messages').css('display', 'block').hide().html('<ul class="errors">' + errors + '</ul>').fadeIn(300);
                        }
                        else{
                                window.location = "/contact-thankyou";
                        }
                }
                else{
                	window.location = "/contact-thankyou";
                }
        }
        else{
              	window.location = "/contact-thankyou";
        }

        $('body').removeClass('wait');
}

$(function(){
	$('form#comment_form').ajaxForm({
		beforeSubmit: validate,
		success: commentResponse
	});


	$('#searchData').example('search charities');
	$('.yourName').example('your name');
	$('.name').example('friend\'s name');
	$('.email').example('friend\'s email address');
	$('.yourEmail').example('your email address');
	$('#signupEmail').example('your email');

	// Initialize and apply FLIR
	FLIR.init({path: '/_assets/flir/'});
	
	$('#finishedBox h3, #confirmBox h3, .loopItem h2, #bodyCopy .causeName, #bodyCopy .mycauseName', $('body').not('#modal')).each(function(){
		FLIR.replace(this, new FLIRStyle({
			mode:"wrap"
		}));
	});

	$('h2, h3, h4, h5, table thead tr th, .itemHeader .date span', $('body').not('#modal')).each(function(){
		FLIR.replace(this);
	});
	
	$('.flir-replaced').each(function(index) {
		var alt = $('.flir-image', this).attr('alt');

		$(this).append('<span class="alt">' + alt + '</span>');
	});

	// Open all external links in new window
	$('a[href^=http]').not('[href^=http://communicause]').not('[href^=http://www.communicause]').bind('click', function(){
		return !window.open(this.href);
	});

	// Hides the inline content if JavaScript is supported.
	$('.hide').hide();

	// Example of preserving a JavaScript event for inline calls.
	$('#click').click(function(){ 
		$('#click').css({
			'background-color':'#f00',
			'color':'#fff',
			'cursor':'inherit'
		}).text('Open this window again and this message will still be here.');
		
		return false;
	});
			
	$("#closeBtn").click(function(){ 
		parent.close_modal();
		return false;
	});
	
	$("#signupBtn").click(function(){
		if( $("#signupEmail").val() != "your email"){
			$.post("/includes/brandmail-signup", { email: $("#signupEmail").val() } );
			$('.pre_submit').hide();
			$('.post_submit').show();
		}
		return false;
	})
	
	$("#retweetBtn").click(function(){ 
		parent.location = "/my-cause/" + $("#charityId").val() + "/complete";
	});
	$("#closeRetweet").click(function(){ 
		parent.location = "/my-cause/" + $("#charityId").val() + "/complete";
		return false;
	});
/*
	$('a[href*="youtube.com"]').each(function(){
		var video = $(this).attr('href');
		video = $.url.setUrl(video).param('v');

		$(this).before('<div class="youtube"></div>');

		$(this).prev('.youtube').flash({
			swf: 'http://www.youtube.com/v/' + video + '&hl=en&fs=1',
			width: 480,
			height: 295,
			hasVersion: 9,
			expressInstaller: '/_assets/swf/expressInstall.swf',
			params: {
				wmode: 'transparent',
				scale: 'noscale',
				allowscriptaccess: 'always',
				allowfullscreen: 'true'
			}
		}).end().remove();
	});
*/	
	$("#confirmNomBtn").click(function() {
		if ( $("#city").val() != "" && $("#state").val() != "" )
		{
			 $("form:last").submit();
		}
		return false;
	});

	$("#confirmVoteBtn").click(function() {
	 	$("form:last").submit();
		return false;
	});
	
	$("#emailFriendBtn").click(function() {
		
	 	if( (  ($("#name1").val() != "friend's name" && $("#email1").val() != "friend's email address") ||
			($("#name2").val() != "friend's name" && $("#email2").val() != "friend's email address") || 
			($("#name3").val() != "friend's name" && $("#email3").val() != "friend's email address")) &&
			$("#emailFriendName").val() != "your name" && $("#emailFriendEmail").val() != "your email address"){
				
				$("#emailFriendForm").submit();
		}
		
		
		return false;
	});
	
    $("#myVote").autocomplete(
            "/ajax/charity_autocomplete",
            {
                    delay:10,
                    minChars:1,
                    matchSubset:1,
                    cacheLength:10,
                    maxItemsToShow:10,
					width:250,
					matchContains:1,
                    autoFill:false
            }
    );

	$("#voteNow").click(function(){
		createModal();

		return false;
	});
	
	$("#voteForm").submit(function(){
		createModal();

		return false;
	});
	
	$('#codeCopy').click(function() {
		$(this).focus().select();
	});
	
	$('#twitterBtn').click(function() {
		pageTracker._trackPageview('/sharing/twitter');
	});
	$('#facebookBtn').click(function() {
		pageTracker._trackPageview('/sharing/facebook');
	});
	$('#myspaceBtn').click(function() {
		pageTracker._trackPageview('/sharing/myspace');
	});
	$('#diggBtn').click(function() {
		pageTracker._trackPageview('/sharing/digg');
	});
	$('#stumbleBtn').click(function() {
		pageTracker._trackPageview('/sharing/stumble_upon');
	});
	$('#delBtn').click(function() {
		pageTracker._trackPageview('/sharing/delicious');
	});
	
	/******** quakbak ***********/
	if ( $("#tweetbacks").length > 0 ) {
			
		$.getJSON("/tb_shorten_lib.php?url=" + "http://communicause.com", function(data){

			search_string = '';
			var urls = new Array;
			u_count = 0;
	
			$.each(data.urls, function(i,item){
				urls[u_count] = item;
				u_count++;

				search_string += item + '+';

			});

			search_string += 'communicause';

			$.getJSON('http://search.twitter.com/search.json?rpp=100&q=&ors=' + search_string + '&callback=?',
			function(twitter_data)
			{
				tweet_backs = '';
				tweet_back_list = '';
				t_count = 0;
				valid_tweetback = false;

				$.each(twitter_data.results, function(i,item){
		
					for (x in urls)
					{
						// see if the URL returned matches one of the URLS we searched for. The Twitter search API is not case sensitive, URL shorteners are. This causes invalid tweetbacks to be returned.
					
						if(item.text.match(urls[x].replace(/\//g, "\\/")) || item.text.match('ommuni'))
						{
							valid_tweetback = true;

						}
		
					}

					if(valid_tweetback)
					{
						tweet_back_list += "<li><a href='http://twitter.com/" + item.from_user + 
										"'><img src='" + item.profile_image_url + "' /><strong>" + 
										item.from_user+":</strong></a> "+item.text+" "+item.created_at+"</li>";
						t_count++;

					}

					valid_tweetback = false;
		
				});

				//tweet_backs = "<b>"+t_count+" Total TweetBacks:</b>";
				tweet_backs = "<ul id='tweet_back_list'>";
				tweet_backs += tweet_back_list;
				tweet_backs += "</ul>";	

				$("#tweetbacks_loading").hide();
				$("#tweetbacks").html(tweet_backs);

			});

		});

	}
	
	
});


function checkVideo(id) {
	var tsTimeStamp= new Date().getTime();
	$.get('/video_check.php', { q: id, time: tsTimeStamp }, function(data){
		if (data == 'true') {
			location.reload(true);
		}
	});
}


$(document).ready(function(){
	//the upcomming posts' ids in EE
	var live_id = 69;
	var canned_id = 68;
	
	var live = $('#live-video');
	var canned = $('#canned-video');
	var announced = $('#announced');
	
	if ( ! live.length && canned.length) {
		//canned video detected, but not live
		setInterval("checkVideo("+live_id+")", 10000);
	}
	else if ( ! canned.length && announced.length) {
		//announcement made, but canned vid not posted yet
		setInterval("checkVideo("+canned_id+")", 10000);
	}
	
	$('#contact_submit').show();
});

