// TODO - BS - Add generic error checking on page load. 
	// Look for error object written by server side into javascript
	// If a custom error handling function is defined for this page, use that, otherwise osme standard notification

function addslashes(str) {
    str=str.replace(/\'/g,'\\\'');
    str=str.replace(/\"/g,'\\"');
    str=str.replace(/\\/g,'\\\\');
    str=str.replace(/\\0/g,'\\0');
    return str;
}

function stripslashes(str) {
    str=str.replace(/\\'/g,'\'');
    str=str.replace(/\\"/g,'"');
    str=str.replace(/\\\\/g,'\\');
    str=str.replace(/\\0/g,'\0');
    return str;
}

function htmlentities(s) {
    var str = new String(s);
    str = str.replace(/&/g, "&amp;");
    str = str.replace(/</g, "&lt;");
    str = str.replace(/>/g, "&gt;");
    return str;
}


/**
 * for panel +/- (vaL 050809)
 */
function panel_toggle(obj){
	var parent = $(obj).parents('.panel');
	var div;
	if(parent.length){
		div = $(parent[0]).children('.panel_body');
		if(div.length){
			$(div[0]).toggleClass('panel_body_hide');	
		}
	}
	
	$(obj).children('.panel_toggle').toggleClass('panel_toggle_plus');
}


$(function (){
	// convenient javascript function for testing "empty"
	$.empty = function( mixed_var ) {

	    var key;

	    if (mixed_var === "" ||
	        mixed_var === 0 ||
	        mixed_var === "0" ||
	        mixed_var === null ||
	        mixed_var === false ||
	        mixed_var === undefined )
		{
	        return true;
	    }

	    if (typeof mixed_var == 'object') {
	        for (key in mixed_var) {
	            return false;
	        }
	        return true;
	    }

	    return false;
	};

	// ajax default error handling

	$.ajaxSetup({
        dataType: "json"
	});

	$.FLAjaxConnectionError = function() {
		$("<p>There was a network or server error. Please try again later.</p>").dialog({title: "Error", modal: true, resizable: false, buttons: { 'Ok': function() { $(this).dialog("close"); } }});
	};

    $(document).ajaxError(function() {
        setTimeout($.FLAjaxConnectionError, 3000);
    });

	// this can be used inside the 
	$.FLCheckAjaxError = function(data) {
		if (!$.empty(data.error_code)) {
			$("<p>" + data.error_message + "</p>").dialog({title: "Error", modal: true, resizable: false, buttons: { 'Ok': function() { $(this).dialog("close"); } }});
			return true;
		} else {
			return false;
		}
	};

	if (jQuery.validator){
		jQuery.validator.addMethod("thisManyNumbers", function(value, element, param) { 
			var pattern = new RegExp('[0-9]{' + param + '}');
		 return this.optional(element) || pattern.test(value);
		}, jQuery.format("Please enter at least  {0} number(s) in your password."));
		jQuery.validator.addMethod("thisManyLetters", function(value, element, param) { 
			var pattern = new RegExp('[a-zA-Z]{' + param + '}');
		 return this.optional(element) || pattern.test(value);
		}, jQuery.format("Please enter at least  {0} letters(s) in your password."));
	}
	
	if(Server.error_code) {
		$("<p>" + Server.error_message + "</p>").dialog({
			title: "Error", modal: true, resizable: false, 
			buttons: { 'Ok': function() { $(this).dialog("close"); } }
		});
	}

	if(Server.info_code) {
		$("<p>" + Server.info_message + "</p>").dialog({
			title: "Information", modal: true, resizable: false, 
			buttons: { 'Ok': function() { $(this).dialog("close"); } }
		});
	}
	
	$("#header_logout").click(function() {
	    try {
	        FB.Connect.ifUserConnected(
	        		function() { FB.Connect.logoutAndRedirect(Server.site_url + '/logout'); },
	        		Server.site_url + '/logout');
	    }
	    catch (e) {
	    	location.href = Server.site_url + '/logout';	    	
	    }
        
	});
	
	$("#verify_email_sent").dialog({
	        title: "Confirmation Email Sent", 
	        dialogClass: "signup", 
	        modal: true, autoOpen: false, width: 500, resizable: false, 
	        buttons: { 
                'Close': function() {
                    $(this).dialog("close");
		        }
	        }
	});

    $('#resend_email_link').click(function(){
        $("#resend_email").ajaxSubmit({
            success : function(data){
                if (data.error_code > 0) {
                    $.FLCheckAjaxError(data);
                }
                else {
                    $("#verify_email_sent").dialog('open');
                }
            },
            error : function () {
                $.FLAjaxConnectionError();
            }
        });
    });

});


Common = {};

Common.init = function(context) {

    /*
     * for tooltips, all elements with a class '.with_tooltip' will get a tooltip
     * the tooltip's text/innerHTML can be the element's "alt" value or its <em> child
     *
     * alt for 'text only' tooltips
     * <em> child is available because sometimes, the 'alt' contains an fb:name (&the like)
     */

    $(".with_tooltip", context).each(function(i) {
        var tooltip_text = $(this).attr('alt');
        if (tooltip_text) {
            $(this).append('<em><span>'+tooltip_text+'</span></em>');
        }
        $(this).css({'position':'relative'});
    });

    $(".with_tooltip", context).hover(function() {
        if($(this).children("em").text()) {
            $(this).children("em").show();
        }
    }, function() {
        $(this).children("em").hide();
    });

    $(".watermark", context).each(function() {
        // For all input text items, remove the grey class and clear the box on focus.
        $(this).focus(function() {
            $(this).filter(function() {
                // We only want this to apply if there's not something actually entered
                return $(this).val() === "" || $(this).val() == $(this).attr('watermark');
            }).removeClass("watermark").val("");
        });

        // When the input item loses focus, add the grey class back and the default text if they haven't entered anything.
        $(this).blur(function() {
            $(this).filter(function() {
                // We only want this to apply if there's not something actually entered
                return $(this).val() === "";
            }).addClass("watermark").val($(this).attr('watermark'));
        });

        var that = this;
        $(this).parents('form').submit(function() {
            // Clear out any fields that still have the watermark
            if ($(that).val() == $(that).attr('watermark')) {
                $(that).val('');
            }
        });

        // Cause watermarks to appear on every field
        $(this).blur();
    });

    // Do we need to ask for any extended permissions?
    if (Server.ask_for_facebook_permission) {
		Server.ask_for_facebook_permission = false; //  It sometimes calls this Common.init() twice... Prevent the dialog from poping up again
		typeof(FB) == "object" && FB.ensureInit(function() {
			FB.Connect.showPermissionDialog("email,publish_stream,read_stream", function(perms) {
			   	// Netdat :)
			   	$.ajax({
			   	  type: "GET",
			   	  url: Server.server_url+'/profile/ajax/update_missing_info',
			   	  data: {netdat:1, perms:perms},
			   	  dataType: "json",
			   	  success: function(data){
			   	  		if (data == 'owned') {
			   	  			$('#missing_info_body').hide();
			   	  			$('#new_password_body').removeClass('hide');
			   	  		}
			   	  		
			   	  		if (data != 'duplicate') {
			   	  			MissingInfoPopup.show(true);
			   	  		}
			   	     },
			   	     error: function(data) {
			   	         $.FLAjaxConnectionError();
			   	     }
			   	 });
			});
		});       	
   	}
   	
   	if (Server.show_missing_info_popup) {
   		MissingInfoPopup.show(false);
   	}
};

Common.report_problem = function(context) {
	var popup = $('#report_problem_box');
	
	$(popup).dialog({
		title: 'Report a Problem', 
	    modal: true,
	    width: 460,
	    resizable: false, 
	    dialogClass: 'ui-dialog-secure', // Add padlock of security to bottom left of dialog
	    buttons: { 
	    	'Cancel': function() {
	    		$(this).find('#report_problem_box_text').val('');
	        	$(popup).dialog('destroy');
	    	},
	        'Report' : function() {
	            var text = $(this).find('#report_problem_box_text').val();
	            $.ajax({
	              type: "GET",
	              url: Server.server_url+'/contactus/ajax/report_a_problem',
	              data: {text:text},
	              dataType: "json",
	              success: function(data){
	              	$('#report_problem_box_text').val('');
	                $(popup).dialog('destroy');
	              },
	              error: function(data) {
	              	$.FLAjaxConnectionError();
	              }
	             });
	         }
	    }
	});
}

$(document).ready(function(){

    Common.init();
    
    $('.form_submit').hover(
        function() {
            $(this).attr('src', Server.static_url+'/images/button_green_submit_hover.png');
        },
        function() {
            $(this).attr('src', Server.static_url+'/images/button_green_submit.png');
        });
	
	//check if the header is `tall_header`
	var isTall = $('.tall_header').length;
	if (isTall) {
		//when it's not the tall header, the page_content_container is padding:75px 0 0
		//because the header is position:absolute
		//but since the tall header is not position:absolute, we don't need that padding
		
		if ($('#page_content_container').hasClass('homepage')) {
			$('#page_content_container').css({'background-position':'100% 0','padding-top':'0'});
		}
		else {
			$('#page_content_container').css({'background-position':'100% 0','padding-top':'50px'});
		}
	}
	
    // TODO: Do we really need this? document.all?
    if (document.all) {
        $('ul.ul_links li').each(function() {
            $(this).bind('mouseover', function() { $(this).addClass('header_nav_rollover_bg');});
            $(this).bind('mouseout', function() { $(this).removeClass('header_nav_rollover_bg'); });
        });
    }
	
	HeaderDropdown.init();
	
	//this are for form buttons that use the embossed buttons to submit its parent's form
	//the embossed buttons are <a> buttons with <span>s in it..
	//it is easier to style them than using <input> or <button>
	$('.form_submit_button').each(function(){
		$(this).click(function(){
			$(this).parents('form').submit();									   
		});
	});

    $('.ul_links a').click(function() {
        typeof(pageTracker) == 'object' && pageTracker._trackEvent('header', $(this).html());
    });

    $('#ghetto_submit_button').click(
        function() {
            // check the client side fields
            var fname = $('#first_name').val();
            var lname = $('#last_name').val();
            var email = $('#email').val();
            var offer = $("input[name='offer']:checked").val();

            var data = {};
            data.error_code = 1;
            if (fname == '' || lname == '' || email == '') {
                data.error_message = 'Please fill out all fields.';
                $.FLCheckAjaxError(data);
                return false;
            }
            else if (!EmailValidation.isValid(email)) {
                data.error_message = 'Please enter a valid email address.';
                $.FLCheckAjaxError(data);
                return false;
            }
            else if (!offer) {
                data.error_message = 'You  must select an offer';
                $.FLCheckAjaxError(data);
                return false;
            }

            // everything is ok so submit
            $('#ghetto_submit_button').addClass('_loading');
            $('#form1').ajaxSubmit({
                success : function(data){
                    if (!$.FLCheckAjaxError(data)) {
                        $("#ghetto_test").dialog("close");
                        $("#ghetto_test_result").dialog({
                            title: "Thanks",
                            modal: true,
                            autoOpen: true,
                            buttons: { "Close": function() { 
                                $(this).dialog("close"); 
                                showing_popup = false; 
                                if (typeof(Tree) != "undefined") {
                                    getBrowserSize(false);
                                }
                            }},
                            height   : 450,
                            width    : 815
                        });
                    }
                    else {
                        $('#ghetto_submit_button').removeClass('_loading');
                    }
                }
            })
    });

    if (($('#popup_tree').html() == 'Yes') && ($('#popup_tree_url').length)) {
        showing_popup = true;
        var popup = $("#ghetto_test");
        popup.dialog({
            title: "Special Offer",
            modal: true,
            autoOpen: false,
            buttons: { "No Thanks": function() { 
                $(this).dialog("close");
                showing_popup = false; 
                if (typeof(Tree) != "undefined") {
                    getBrowserSize(false);
                }
            }},
            minHeight: 710,
            height   : 710,
            width: 815,
            minWidth: 815
        }); 
        popup.dialog('open');
    }
    else {
        if (typeof(Tree) != "undefined") {
            getBrowserSize(false);
        }
    }

});

var Notify = {};
Notify.stream_post = function(type,passvar,url){
		$.ajax({
          type: "GET",
          url: Server.server_url+"/post_stream/ajax/postit",
          data: {type:type,passvar:passvar,url:url},
          dataType: "json",
          success: function(data){
             if (data.publish === 1) {
			   var attachment = {'name':data.name,
			                     'href':data.href,
								 'description':data.description,
								 'media':[{'type':'image','src':data.img,'href':data.href}]};
			   FB.Connect.streamPublish('',attachment,null,null,null,null,Server.can_auto_publish);
			 }
            }
         });
};

Notify.wall_to_wall = function(type,profile_id,url,callback){
    if (typeof(callback) == 'undefined') {
        callback = null;
    }
	$.ajax({
      type: "GET",
      url: Server.server_url+"/post_stream/ajax/postit",
      data: {type:type,profile_id:profile_id,url:url},
      dataType: "json",
      success: function(data){
         if (data.publish === 1) {
		   var attachment = {'name':data.name,
		                     'href':data.href,
							 'description':data.description,
							 'media':[{'type':'image','src':data.img,'href':data.href}]};
		   FB.Connect.streamPublish('',attachment,null,data.fbid,null,callback,Server.can_auto_publish);
		 }
        }
     });
};

var EmailValidation = {};
EmailValidation.isValid = function(email) {
    regex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;
    return regex.test(email);
};

var Log = {};
Log.event = function(event) {
	$.ajax({
	  type: "GET",
	  url: Server.server_url+"/log/ajax/"+event,
	  data: {},
	  dataType: "json",
	  success: function(data){
          //
	    }
	 });
};

// If the user is already connected with Facebook, try to log them in directly.
function fb_auto_login() {
	typeof(FB) == "object" && FB.ensureInit(function() {
		FB.cancel_auto_login = false;
		FB.Connect.get_status().waitUntilReady( function( status ) {
	    	switch ( status ) {
	        case FB.ConnectState.connected:
	        case FB.ConnectState.userNotLoggedIn:
	        		FB.Facebook.get_sessionWaitable().waitUntilReady( function (session ) {
	        			// Make sure the auto login hasn't been cancelled before redirecting.
	        			if (!FB.cancel_auto_login) {
	        				window.location = Server.site_url+'/login/2002.2/'+Server.next_page;
	        			}
	        		});
	            break;
	        case FB.ConnectState.appNotAuthorized:
	        	// Prevent infinite redirect
	        	if (!Server.redirected_to_allow_page) {
	        		window.location = Server.site_url+'/allow/'+Server.next_page;
	        	}
	        	break;
            default: break;
	        }
	    });
	});
}

// Allow a script to cancel the auto login if it needs to be able to handle the FB session itself.
function fb_auto_login_cancel() {
	typeof(FB) == "object" && FB.ensureInit(function() {
		FB.cancel_auto_login = true;
	});
}

function fb_auto_logout() {
    typeof(FB) == "object" && FB.ensureInit(function () {
        FB.Connect.ifUserConnected(function() {}, '___SITE_URL___/logout');
    });
}

var MissingInfoPopup = {};
MissingInfoPopup.show = function(askForPassword) {

	var popup = $('#missing_account_info_popup');

    $(popup).dialog({
    	title: 'Your Missing Details', 
        modal: true,
        width: 440,
        resizable: false, 
        dialogClass: 'ui-dialog-secure', // Add padlock of security to bottom left of dialog
        buttons: { 
       		'Cancel': function() {
           		$(popup).dialog('destroy');
           	},
            'Update Account' : function() {
            	if (askForPassword) {
            		if ($('#missing_info_body').is(":visible")) {
            			$('#missing_info_form').ajaxSubmit({
            				success: function(data){
            					if (data == 'duplicate' || data == 'noEmail') {
            						window.location.reload(true);
            					}
            					else if (!$.FLCheckAjaxError(data)) {
            						$('#missing_info_body').hide();
            						$('#new_password_body').removeClass('hide');
            					}
            				}
            			});
            		}
            		else if ($('#new_password_body').is(":visible")) {
            			$('#new_password_form').ajaxSubmit({
            				success: function(data){
            					if (!$.FLCheckAjaxError(data)) {
            						window.location.reload(true);
            					}
            				}
            			});
            		}
            	}
            	else {
            		if ($('#missing_info_body').is(":visible")) {
            			$('#missing_info_form').ajaxSubmit({
            				success: function(data){
            					if (!$.FLCheckAjaxError(data)) {
            						window.location.reload(true);
            					}
            				}
            			});
            		}
            	}
         	}
    	}
    });
    	    
   	new AjaxUpload('#upload_new_profile_pic', {
   		action: Server.server_url+'/getting_started/ajax/upload_photo',
   		name: 'profile_picture',
   		autoSubmit: true,
   		responseType: false,
   		onChange: function(file, extension){},
   		onSubmit: function(file, extension) {
   			$('#loading_text').html('Uploading...');
   			$('#upload_new_profile_pic').hide();
   		},
   		onComplete: function(file, response) {
   			$('#loading_text').html('');
   			$('#upload_new_profile_pic').show();
   			if (response) {
   		    	var r = response.split(',');
   		            
   		        if (r[1]) {
   		        	$('#profile_pic_holder').show();
   		        	$('#profile_pic_holder').attr('src',r[1]);
   		        }
   			}
   		}
   	});
   				   	     
 		// Override the default submit function	
   	$('#missing_info_form').submit(function(){
   		return false;
   	});
   	
   	$('#new_password_form').submit(function(){
   		return false;
   	});
};

/*
 * header dropdowns
 */
var HeaderDropdown = {};
HeaderDropdown.init = function(){
	var timeoutInt;
	$('.header_menu_dropdown').each(function(){
		var dropdown = $(this);
		dropdown.mouseover(function(){
			/*
			 * hide others
			 */
			$('.header_menu_dropdown').each(function(){
				if ($(this) != dropdown) {
					$(this).parent().removeClass('header_menu_dropdown_active');
				}
			});
			
			if (timeoutInt) {
				clearTimeout(timeoutInt);
			}
			dropdown.parent().addClass('header_menu_dropdown_active');
		});
		
		dropdown.mouseout(function(){
			timeoutInt = setTimeout(function(){  
				dropdown.parent().removeClass('header_menu_dropdown_active');
			}, 500);
		});
	});
	
	$('.header_menu_dropdown_links').each(function(){
		var dropdown_links = $(this);
		dropdown_links.mouseover(function(){
			if (timeoutInt) {
				clearTimeout(timeoutInt);											   
			}
			dropdown_links.parent().addClass('header_menu_dropdown_active');
		});
		
		dropdown_links.mouseout(function(){
			timeoutInt = setTimeout(function(){
				dropdown_links.parent().removeClass('header_menu_dropdown_active'); 					  
			}, 500);
		});
	});
};
