/**
 * jQuery crop - takes (IMG) elements and crops them to the dimensions
 * given.  The result is the same image with a background image with the
 * height and width and an offset.  The new DIV should also carry across
 * the existing style attributes of the image.
 *
 * @author Remy Sharp (leftlogic.com)
 * @date 2006-12-28
 * @example $("img").crop(x, y, height, width)
 * @example $("img").crop({ x: x, y: y, height: height, width: width })
 * @example $("img").crop(height, width)
 * @example $("img").crop(width)
 * @desc Crops image to dimensions given.  If only width (and height),
 * x and y are selected randomly based on the image's height and width.
 *
 * @name crop
 * @type jQuery
 * @param Number x co-ordinate to start crop
 * @param Number y co-ordinate to start crop
 * @param Number height of final cropped image
 * @param Number width of final cropped image
 * @cat Plugin
 */
// jquery-specific script: packed - version control has latest version!
$(document).ready(function() {
    /*** Start:Header Console setup ***/
    // populate the form elements with help text, etc
    if (!document.getElementById || !document.createTextNode) return;
    if (document.getElementById("scrapbookWeatherInner")) {
        hl.init();
        ip.init();
    }
    /*** Page specific jQuery ***/
    //$("#sideChangeLoc").clearInput();
    $("#printJS").show();
    externalWindow("a[rel*='external']");
    /*** SIFR Replacement ***/
    //sIFR.replace(glyphaBold, {selector: '.sifr18', css: ['.sIFR-root { text-align: left; font-size: 15px; color: #172d02; }', 'a { text-decoration: none; }', 'a:link { color: #172d02; }', 'a:hover { color: #172d02; }'], wmode: 'transparent'});
	if( $(".recentComments .more") ) {
		recentPlantComments();
	}
	$('#buyThisPlant li:first-child').addClass('first');
	$('#buyThisPlant li:last-child').addClass('last');
});
/*
 CLEAR INPUT FIELD FUNCTION
 http://bassistance.de/2007/01/23/unobtrusive-clear-searchfield-on-focus/
 */
$.fn.clearInput = function() {
    return this.focus(function() {
        if (this.value == this.defaultValue) {
            this.value = "";
        }
    }).blur(function() {
        if (!this.value.length) {
            this.value = this.defaultValue;
        }
    });
};
/*
 EXTERNAL WINDOWS
 */
function externalWindow(theElement) {
    $(theElement).click(function() {
        window.open(this.href);
        return false;
    });
}
;
/*
 CONSOLE FUNCTIONS
 This is a collection of action that need to be performed on the header console when you click open
 */
// start: prepare login forms
ip = {
    init : function () {
        ip.defaultColor();
        //ip.labelFocus();
        // if(document.getElementById("password")){
        //  ip.pwdPrepare(document.getElementById("password"));
        // }
    },
    defaultColor : function () {
        var scrapbook = document.getElementById("scrapbookWeatherInner");
        var fields = scrapbook.getElementsByTagName("input");
        //for( var i=0; i<fields.length; i++){
        //	fields[i].style.color = "#999";
        //}
    },
    // needs to be like this for IE6...
    changeInputType : function (oldObject, oType) {
        var newObject = document.createElement('input');
        newObject.type = oType;
        if (oldObject.value) newObject.value = oldObject.value;
        if (oldObject.size) newObject.size = oldObject.size;
        if (oldObject.name) newObject.name = oldObject.name;
        if (oldObject.id) newObject.id = oldObject.id;
        if (oldObject.className) newObject.className = oldObject.className;
        oldObject.parentNode.replaceChild(newObject, oldObject);
        return newObject;
    },
    // TODO: password functions need looking at: onblur is only working every 2nd time...
    // pwdPrepare : function (pwdObj) {
    //   if(pwdObj.value == ""){
    //      pwdObj.value = "Enter password";
    //      var newObj = ip.changeInputType(pwdObj, "text");
    //      newObj.style.color = "#999";
    //      newObj.focus();
    //      ip.pwdFocus(newObj);
    //    }
    // },
    // pwdFocus : function (pwdObj){
    //  pwdObj.onfocus = function() {
    //    if(this.value == "Enter password"){
    //      this.value = "";
    //      var newObj = ip.changeInputType(this, "password");
    //      newObj.style.color = "#000";
    //      newObj.focus();
    //      ip.pwdBlur(newObj);
    //    }
    //  };
    // },
    // pwdBlur : function (pwdObj) {
    //  pwdObj.onblur = function() {
    //    if(this.value == ""){
    //      this.value = "Enter password";
    //      var newObj = ip.changeInputType(this, "text");
    //      newObj.style.color = "#999";
    //      ip.pwdFocus(newObj);
    //    }
    //  };
    // },
    labelFocus : function () {
        var scrapbook = document.getElementById("scrapbookWeatherInner");
        var fields = scrapbook.getElementsByTagName("input");
        for (var i = 0; i < fields.length; i++) {
            var currentField = fields[i];
            if (currentField.getAttribute("type") == "text" || currentField.getAttribute("type") == "password") {
                currentField.onfocus = function() {
                    if (this.value == this.defaultValue) {
                        this.value = "";
                        this.style.color = "#000";
                    }
                };
                currentField.onblur = function() {
                    if (this.value == "") {
                        this.value = this.defaultValue;
                        this.style.color = "#999";
                    }
                };
            } else {
                continue;
            }
        }
        /*var changeLoc = document.getElementById("changeLocation");
         changeLoc.onfocus = function(){
         if( this.value == this.defaultValue ){
         this.value = "";
         this.style.color = "#000";
         }
         };
         changeLoc.onblur = function(){
         if( this.value == "" ){
         this.value = this.defaultValue;
         this.style.color = "#999";
         }
         };*/
    }
};
var suppressConsoleHide = false;
hl = {
    init : function () {
        //fix the Subscribe sifr on load
        sIFR.replace(glyphaBold, {selector: '.sifr18', css: ['.sIFR-root { text-align: left; font-size: 15px; color: #172d02; }', 'a { text-decoration: none; }', 'a:link { color: #172d02; }', 'a:hover { color: #172d02; }'], wmode: 'transparent'});
        // Fix the labels on the login console
        var usernameLabel = $("#scrapbookWeather label.cplat-username-label");
        var passwordLabel = $("#scrapbookWeather label.cplat-password-label");
        //usernameLabel.addClass("hidden");
        //passwordLabel.addClass("hidden");
        //$("#scrapbookWeather input#cplat_usernameLogin").attr("value", usernameLabel.text());
        //$("#scrapbookWeather input#cplat_passwordLogin").attr("value", passwordLabel.text());
        //$("#scrapbookWeather input#cplat_passwordLogin").attr("type", "input");
        /*$("input#cplat_usernameLogin").focus(
         function() {
         $(this).attr("value", "");
         }
         );
         $("input#cplat_usernameLogin").blur(
         function() {
         if ($(this).text()=="") {
         $(this).attr("value", usernameLabel.text());
         $(this).style.color="#999";
         }
         }
         );*/
        $("li.signin a").click(function() {
            hl.consoleHandling("open");
            return false;
        });
        $("#chngLocLink a").click(function() {
            hl.consoleHandling("open");
            return false;
        });
        $("p#openCloseTab a").click(function() {
            hl.consoleHandling("openClose");
            return false;
        });
        $("a.forgottenDetails").click(function() {
            hl.showEmailReminder();
            return false;
        });
        if (! suppressConsoleHide) {
            this.closeConsole();
        }
    },
    showLoginForm : function () {
        if ($("form#emailReminder").is(':visible')) {
            $("form#emailReminder").slideUp("slow");
        }
        $("div.scrapbook ul").slideUp("slow");
        $("#loginForm").slideDown("slow");
    },
    showEmailReminder : function () {
        if ($("#loginForm").is(':visible')) {
            $("#loginForm").slideUp("slow");
        }
        $("form#emailReminder").slideDown("slow");
    },
    openConsole : function (el) {
        if (el == "login" || el == "") {
            hl.showLoginForm();
        } else if (el == "reminder" || el == "emailNotFound") {
            hl.showEmailReminder();
        }
        $(".slideMe").slideDown("slow");
        $("#magHeadLowerLarge").slideDown("slow");
        $("#magHeadLowerSmall").slideUp("fast");
        $("p#openCloseTab").css("background-position", "0 24px");
    },
    closeConsole : function () {
        if ($("form#emailReminder").is(':visible')) {
            $("form#emailReminder").slideUp("slow");
        }
        else {
            $("div.scrapbook ul").slideDown("slow");
            $("#loginForm").slideUp("slow");
        }
        $("#chngLocation").slideUp("slow");
        $("#magHeadLowerLarge").slideUp("slow");
        $("#magHeadLowerSmall").slideDown("slow");
        $("p#openCloseTab").css("background-position", "0 0");
    },
    // rather than calling the console functions directly, call this function!
    consoleHandling : function (action) {
        if (action == "openClose") {
            if ($("#loginForm").is(':visible') || $("#emailReminder").is(':visible') || $("#chngLocation").is(':visible'))
                action = "close";
            else
                action = "open";
        }
        if (action == "open" || action == "emailReminderSent" || action == "signInError" || action == "weatherError") {
            var elem = "login";	// determines which element is shown when the console opens
            hl.openConsole(elem);
            sIFR.replace(glyphaBold, {selector: '.sifr18', css: ['.sIFR-root { text-align: left; font-size: 15px; color: #172d02; }', 'a { text-decoration: none; }', 'a:link { color: #172d02; }', 'a:hover { color: #172d02; }'], wmode: 'transparent'});
        }
        if (action == "close") {
            hl.closeConsole();
        }
        if (action == "emailNotFound") {
            hl.openConsole(action);
        }
    },
    //set the anchor div in request and then call consoleHandling function
    consoleHandlingAnchorDiv : function (action, divName, document) {
        if (document.getElementsByName("anchorDiv")[0] != undefined) {
                document.getElementsByName("anchorDiv")[0].value = divName;
        }
        hl.consoleHandling(action);
    }
};
/*** End:Header Console ***/
/*
 The following function forces the page to redraw an element on the page once the entire page (not just the DOM) has loaded.
 This is to get around a Firefox issue whereby it didn't align absolutely positioned elements properly after sIFR had loaded.
 */
$(window).bind('load', function() {
    $("h1 a").addClass("layout");
    /* Hiding Ad text if no ad is pulled in */
    //if ( ($("#mpu embed").length == 0) && ($("#mpu img").length == 0) ) { $("#mpu").css("display","none"); }
    if (($("#skyscraper embed").length == 0) && ($("#skyscraper img").length == 0)) {
        $("#skyscraper p").css("display", "none");
    }
});
function recentPlantComments() {
    $("<p class=\"show\"><a href=\"#\">Show more</a></p>").insertBefore(".recentComments .more div p.join");
	$(".recentComments div#moreComments").slideUp();
    $(".recentComments .more p.show").click(function() {
		if ($(".recentComments div#moreComments").is(":visible")) {
			$(".recentComments div#moreComments").slideUp();
			$(".recentComments .more p.show a").text("Show more");
		} 
		else {
			$(".recentComments div#moreComments").slideDown();
			$(".recentComments .more p.show a").text("Show less");			
		}
		return false;
	});
}
