/**
* Javascript for site-wide functionality
*
* @package js
* @author Tim Carr
* @version 1
* @copyright fish in a bottle 2009
*/

// Additional string parsing
String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
}

String.prototype.ltrim = function() {
    return this.replace(/^\s+/,"");
}

String.prototype.rtrim = function() {
    return this.replace(/\s+$/,"");
}

$(document).ready(function() {
    // Inline Search Box - css changes and focus
    $("input[name=inlineSearch]").addClass("grey");
    $("input[name=inlineSearch]").bind("focus", function (e) {
        if ($(this).hasClass('grey')) {
            $("input[name=inlineSearch]").removeClass("grey");
            $(this).val(''); 
        }
    });
    
	// FCKEditor Validate plugin for jQuery - Validates FCKEditor instances, as jQuery Form Plugin causes issues
    if(typeof jQuery.fn.fckEditorValidate == 'function') {
		jQuery.fn.fckEditorValidate({instanceName: 'content'});
		jQuery.fn.fckEditorValidate({instanceName: 'content0'});
		jQuery.fn.fckEditorValidate({instanceName: 'content1'});
        jQuery.fn.fckEditorValidate({instanceName: 'content2'});
        jQuery.fn.fckEditorValidate({instanceName: 'content3'});
        jQuery.fn.fckEditorValidate({instanceName: 'content4'});
        jQuery.fn.fckEditorValidate({instanceName: 'content5'});
		jQuery.fn.fckEditorValidate({instanceName: 'comments'});
	}
    
	// Character Count Classes
    if(typeof jQuery.fn.charCounter == 'function') {	
	    $(".countCharacters140").charCounter(140);
        $(".countCharacters200").charCounter(200);
	    $(".countCharacters500").charCounter(500);
	    $(".countCharacters1000").charCounter(1000);
	    $(".countCharacters1500").charCounter(1500);
	    $(".countCharacters2000").charCounter(2000);
	    $(".countCharacters").charCounter(2000); // Legacy, keep
	}
        
    /** Logon and Search Boxes **/
    // Username
    $("input[name=username]").addClass("grey");
    $("input[name=username]").bind("focus", function (e) {
        if ($(this).hasClass('grey')) {
            $("input[name=username]").removeClass("grey");
            $(this).val(''); 
        }
    });	
	
	// Remember Me - check / uncheck checkbox.  Livequery, as it can come in and out of DOM scope if user clicks forgot password button
	$("img.rememberMe").bind("click", function (e) {
		if (eval($("input[@name=rememberMe]").attr("checked"))) {
			$("input[@name=rememberMe]").attr("checked", false);									   
		} else {
			$("input[@name=rememberMe]").attr("checked", true);	
		}
	});
	
	// Password
    /* If the password field is there do the following with it */	
	if ($("input[name=password]").length > 0) {		
        $("input[name=password]").replaceWith('<input type="text" name="password" id="password" value="Password" tabindex="2" class="password" />');		
        $("input[name=password]").addClass("grey");        
	}	
	$("input[name=password]").bind("focus", function (e) {													  
		var pass = $("input[name=password]").val();		
		if (pass == 'Password') {			
			$("input[name=password]").replaceWith('<input type="password" name="password" id="password" value="" tabindex="2" class="password" />');
			$("input[name=email]").removeClass("grey");
            $("input[name=password]").focus();		
		} // end if
	});	
	
    // Email
    $("input[name=email]").addClass("grey");
    $("input[name=email]").bind("focus", function (e) {
        if ($(this).hasClass('grey')) {
            $("input[name=email]").removeClass("grey");
            $(this).val(''); 
        }
    });
    
     // Main Search Box - css changes and focus
    $("input[name=search]").addClass("grey");
    $("input[name=search]").bind("focus", function (e) {
        if ($(this).hasClass('grey')) {
            $("input[name=search]").removeClass("grey");
            $(this).val(''); 
        }
    });
    
	$("input[name=search]").bind("focus", function (e) {
		var searchVar = $("input[name=search]").val();
		if (searchVar == 'Search') $("input[name=search]").val('');
	});
		
	// Login
	$("#loginButton").bind("click", function (e) {											  
		var user = $('#username').val();		
		var pass = $('#password').val();
		var rememberMe = eval($("input[@name=rememberMe]").attr("checked"))
		
		$.post(
			"ajax/ajax.Login.php",
		   	{
				username: user,
				password: pass,
				rememberMe: rememberMe
		   	},
		   	function (data, textStatus) {
				if (textStatus == "success") {
					if (data.substring(0,5) == "Email" || data.substring(0,5) == "Wrong") {
						// Error
						// Clear fields
						$("input[name=username]").val('');
						$("input[name=password]").val('');
						
						// Show alert
						softAlert(data, alertOff);
					} else {
						// Success
						softAlert(data, function(){
                            window.location = document.location.href;
                        });
					}						
				} else {
					// jQuery Error
					softAlert("A "+textStatus+" error occured.  Please try again.", alertOff);
				}
		   	}
		);
		
		return false; // Prevent submit
	});
	
	// Lost Password
	$("#forgotButton").bind("click", function (e) {
		var email = $('#email').val();
			
		$.post(
			"ajax/ajax.ForgotPassword.php",
		   	{
				email: email
		   	},
		   	function (data, textStatus) {
				if (textStatus == "success") {
					softAlert(data, alertOff);						
				} else {
					// jQuery Error
					softAlert("A "+textStatus+" error occured.  Please try again.", alertOff);
				}
		   	}
		);
		
		return false; // Prevent submit
	});
	
	// Lost Password Toggle DIV
	$("#forgetPasswordButton").bind("click", function (e) {
		$("#loginForm").hide();
		$("#forgotPasswordForm").show();
	});
	
	// Back To Login Toggle DIV
	$("#backToLoginButton").bind("click", function (e) {
		$("#forgotPasswordForm").hide();
		$("#loginForm").show();		
	});	
	
	// Login Alert <a> menu link	
	$(".loginAlert").bind("click", function (e) {
		softAlert("Please log in.<br />If you're not a member <a href=\"join\" title=\"Join Now\">click here to join now</a>.", alertOff);
	});
        
    // Report Abuse Button - Report to Moderators.
    $(".reportAbuseToModerators").livequery("click", function(e) {
        var groupID = $("input[@name='groupID']").val();
        softConfirm("Send abuse report now?", 
                    function(){
                        // User clicked Yes - run jQuery POST to report
                        $.post(
                            "ajax/ajax.ReportAbuse.php",
                            {
                                action: 'reportToModerators',
                                groupID: groupID,
                                url: document.location.href
                            },
                            function (data) {
                                // Show Confirmation
                                if (data == 1) {
                                    softAlert("Abuse reported", alertOff);
                                } else {
                                    softAlert("An error occured when reporting abuse.  Please try again.", alertOff);    
                                }
                            }
                        )
                        // Hide alert box
                        alertOff();
                    }, 
                    alertOff);
    });
    	
	// Report Abuse Button
    $(".reportAbuse").livequery("click", function(e) {
        // Element id of report abuse button should be in the format table-primaryKey (underscore reserved for mysql table names)
        abuseDetails = $(this).attr("id").split("-");
        
        softConfirm("Send abuse report now?", 
                    function(){
                        // User clicked Yes - run jQuery POST to report
                        $.post(
                            "ajax/ajax.ReportAbuse.php",
                            {
                                action: 'report',
                                table: abuseDetails[0],
                                primaryKey: abuseDetails[1],
                                url: document.location.href
                            },
                            function (data) {
                                // Show Confirmation
                                if (data == 1) {
                                    softAlert("Abuse reported", alertOff);
                                } else {
                                    softAlert("An error occured when reporting abuse.  Please try again.", alertOff);    
                                }
                            }
                        )
                        // Hide alert box
                        alertOff();
                    }, 
                    alertOff);
    });
    
    // Disable all input image buttons when a form with class=disableButtonsOnSubmit is submitted, to prevent multiple saving
    $('form.disableButtonsOnSubmit').bind('submit', function(e) {
        $(this).find('input[type=image]').each(function(i) {
            $(this).attr('disabled', true);
        });
    });
    
    // Links with a.userLink are links that users have generated in content
    // Check if the link goes to an external site, and if it does, warn the user about the danger
    // of external web sites
    /*
    $('a.userLink').bind('click', function(e) {
        e.preventDefault();
        var url = $(this).attr('href');        
        if (url.search('http://www.gardenersclick.com') == -1) {
            // Not a gc link
            softConfirm('This link goes to an external web site.  Never share any personal details, and exercise caution.<br />Do you want to continue?',
                        function() {
                            // OK
                            window.open(url);
                            alertOff();
                            return true;
                        },
                        function() {
                            // Cancel
                            alertOff();
                            return false;
                        });
        }
    });
    */
    
    // Image Rollover Mappings - map class=RollOverImage to legacy autoRoll JS functions
	$(".RollOverImage").mouseover(function(e) { autoRoll(this); });	
	$(".RollOverImage").mouseout(function(e) { autoRollOut(this); });  
});

// Paginator
function GetPage(pageNo, refreshArea, callClass, callClassFunction, callClassFunctionArguments) {
    // Show loading indicator
    $(refreshArea).html("<h3>Loading, please wait...</h3><p><img src=\"/images/indicator.gif\" width=\"16\" height=\"16\" alt=\"Loading..\" /></p>");
    
	$.post(
		   "ajax/ajax.Pagination.php",
		   {                                                                                                                                                
				pageNo: pageNo,
				callClass: callClass,
				callClassFunction: callClassFunction,
				callClassFunctionArguments: callClassFunctionArguments
		   },
		   function (data) {
			   	// Load data into refresh area
				$(refreshArea).html(data);
                
                // Rebind prettyCheckboxes for to do lists
                if(typeof jQuery.fn.prettyCheckboxes == 'function') {
                    $('input.selectAnswerCheckbox').prettyCheckboxes({
                        checkboxWidth: 40,
                        checkboxHeight: 40
                    });
                }
				
				// Rebind prettyCheckboxes to their input class selectors (e.g. questions page - choosing answer(s)), and re-check checkboxes
				// based on the selectedAnswerIDs() Array in questions.js
				/*
                if(typeof jQuery.fn.prettyCheckboxes == 'function') {
					$('input.selectAnswerCheckbox').prettyCheckboxes({
                        checkboxWidth: 40,
                        checkboxHeight: 40
                    });
					for (i = 0; i < selectedAnswerIDs.length; i++) {
						if (selectedAnswerIDs[i] != null) {
							// Hidden input checkbox, but check it for completeness
							$("input[@name='answer["+selectedAnswerIDs[i]+"]']").attr("checked", true); 
							
							// prettyCheckboxes uses label class=... checked to denote the checkbox is ticked.
							// Get the parent div.answerCheckbox, and then get its child label (i.e the label which controls the prettyCheckboxes)
							$("input[@name='answer["+selectedAnswerIDs[i]+"]']").parent("div.answerCheckbox").children("label").addClass("checked");
						}
					}
				}
                */ 				
		   }
	);
}

// Get base HREF
function getBase(){
	return document.getElementsByTagName('base')[0].href;
}