/*
--------------------------------------------------

MyHome@UL
application.js

David Munger [david.munger@acquitygroup.com]
9/18/2008

Copyright 2008 Acquity Group LLC

--------------------------------------------------
*/

$(document).ready(function() {
	
	// search field prompt fanciness
	$("#searchControl input").focus(function() {
		if ($(this).val() == "Search UL.com")
		{
			$(this).val("");
		}
	});

	$("#searchControl input").blur(function() {
		if ($(this).val() == "")
		{
			$(this).val("Search UL.com");
		}
	});


	// expanding menu items for action list details, e.g. in "My Dashboard"
	$("ul.actionList li a.actionLink").click(function() {
		
		$(this).next("ul.actionDetails").slideToggle("fast");
	})

	// load custom select fields
	$("#perspective, #location, #industry, #serviceline, #filterBy, #doctype, #sortBy, #resultsperpage, fieldset.dropdown select").selectbox();

	/* Handle the hiding and showing of the box controls */
	
	// We turn the collapsed, clickable box area on here,
	// so it degrades gracefully.. we don't want this to show
	// if we're showing the box stuff in <noscript>
	$("#boxCollapsedAlert").hide();
	$("#boxExpandedFavorites").hide();
	
	$("#boxCollapsedAlert").click(function () {
		$(this).hide();
		$("#boxExpandedAlert").show();
	});
	
	$("#boxExpandedAlert a#myExpandedAlerts").click(function () {
		$("#boxExpandedAlert").hide();
		$("#boxCollapsedAlert").show();
	});

	$("#boxCollapsedFavorites").click(function () {
		$(this).hide();
		$("#boxExpandedFavorites").show();
	});
	
	$("#boxExpandedFavorites a").click(function () {
		$("#boxExpandedFavorites").hide();
		$("#boxCollapsedFavorites").show();
	});
	

/* End hiding and showing box controls */

});
 
 // Show/Hide functionality via JQuery for My Alerts
$(document).ready (function () {
    $(".detail").hide();
    $(".myAlert").wrapInner("<a href='javascript:;'></a>");
    $(".myAlert").click(function () {
        $("#d" + $(this).attr("id").replace("m", "")).toggle(100);
    });
});

//FAQ Function - deprecated
function doFAQ(num) {
  if (document.getElementById(num).className == "detail") {
    document.getElementById(num).className = "aunhidden";
  } else {
    document.getElementById(num).className = "detail";
  }
}

/* Suckerfish function for IE, to allow focus on non-a tags */
sfHover = function() {
	var sfEls = null;
        if (document.getElementById("mainNav") != null) {
          sfEls = document.getElementById("mainNav").getElementsByTagName("LI");
	  for (var i=0; i<sfEls.length; i++) {
	  	sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	  }
        }
}

if (window.attachEvent) window.attachEvent("onload", sfHover);

// 4. JQuery Functions
//---------------------------------------------------------------------------------------------------
// The Following functions use the JQuery library for better/faster processing
// Thanks to Ryan Spradlin for quick work on these
//---------------------------------------------------------------------------------------------------

// Google Analytics tracking of outgoing links - uses JQuery
// Needs to exclude local links (particularly for Edit and sso related logout type links
$(document).ready(function() {
    $("a").click(function() {
        var regex = new RegExp("^javascript:|(http:\\/\\/(my\\.home\\.ul\\.com|my\\.home1\\.ul\\.com|my\\.homedev\\.ul\\.com|my\\.homeqa\\.ul\\.com|usmela910s|sso\\.))", "i");
        var thishref = $(this).attr("href");
        if (thishref && !(thishref.match(regex))) {
            if (typeof(pageTracker) == "object") {
                pageTracker._trackPageview("/outgoing/" + thishref);
            }
        }
/* Removed default true return so confim onclick events work  */
      /* return true; */
    });
});

// FAQ functionality via JQuery
$(document).ready (function () {
    $(".answer").hide();
    $(".question").wrapInner("<a href='javascript:;'></a>");
    $(".question").click(function () {
        $("#a" + $(this).attr("id").replace("q", "")).toggle(100);
    });
});

// Expand All FAQs
function expandAllFAQs() {
  $(".answer").slideDown();
}

// Collapse All FAQs
function collapseAllFAQs() {
  $(".answer").slideUp();
}

// Expand All Alerts
function expandAllAlerts() {
  $("ul.actionDetails").slideDown();
}

// Collapse All Alerts
function collapseAllAlerts() {
  $("ul.actionDetails").slideUp();
}

// Change background color for native buttons
$(document).ready(function () {
    $("input[type='button'], input[type='submit']").css("background-color", "#ffcc33");
});

// Automatic example code support code
// -----------------------------------
$(document).ready(function () {
    $(".example").each(function (i) {
        $(this).after('<div class="examplecodearea"><span class="exampletitle">Code</span><textarea class="examplecode" wrap="off" readonly="readonly">' + $(this).html() + '</textarea></div>');
    });
});

// CSS reflection support code
// ---------------------------
function cssReflect(sheetname) {
    // Find the stylesheet we need
    var sheet;
    sheetregex = new RegExp(sheetname + "$", "i");
    for (var i = 0; i < document.styleSheets.length; i++) {
        if (document.styleSheets[i].href && document.styleSheets[i].href.match(sheetregex)) {
            sheet = document.styleSheets[i];
        }
    }
    
    // Create output
    var output = $("<table class='sectionTable'><thead><tr class='headerBack'><th>Affected Tags</th><th>Styles</th><th>Demo</th></tr></thead><tbody></tbody></table>");
    var realcount = 0;
    $.each(((sheet.cssRules) ? sheet.cssRules : sheet.rules), function (i, val) {
        // Parse selector -- only simple selectors "like tagname.classname" are supported
        var sel = val.selectorText.match(/^(\w*)(\.(\w+))?$/i);
        if (sel) {
            var seltag = sel[1];
            var selclass = sel[3];
            
            // Natural language selector
            var naturalsel = "";
            naturalsel += (seltag) ? "All <span class='reflectcode'>&lt;" + seltag + "&gt;</span> tags" : "All tags";
            naturalsel += (selclass) ? " with the class <span class='reflectcode'>" + selclass + "</span>" : "";
            
            // Make html list of rules
            var rules = val.style.cssText.split(";");
            var ruleshtml = "";
            $.each(rules, function (i, val) {
                if (val = $.trim(val)) {
                    ruleshtml += "<li>" + val + "</li>";
                }
            });
            ruleshtml = "<ul>" + ruleshtml + "</ul>";
            
            // Add row to table
            seltag = (seltag) ? seltag : "span";
            var demohtml = "<div class='reflectdemo'><" + seltag + " class='" + selclass + "'>Demo Text</" + seltag + "></div>";
            if (seltag.match(/table|tr|td/i)) demohtml = "<div class='reflectnodemo'>Unable to display demo: this is a table style.</div>";
            /*
            if (seltag == "table") {
                demohtml = "<" + seltag + " class='" + selclass + "'><tbody><tr><td>Demo Table Cell</td></tr></tbody></" + seltag + ">"; alert(demohtml);
            } else if (seltag == "tr") {
                demohtml = "<table><tbody><" + seltag + " class='" + selclass + "'><td>Demo Table Cell</td></" + seltag + "></tbody></table>"; alert(demohtml);
            } else if (seltag == "td") {
                demohtml = "<table><tbody><tr><" + seltag + " class='" + selclass + "'>Demo Table Cell</" + seltag + "></tr></tbody></table>"; alert(demohtml);
            }
            */
            
            // Alternate row?
            var altrow = (realcount % 2) ? " class='rowAlt'" : "";
            realcount++;
            
            $("tbody", output)
                .append("<tr" + altrow + ">" +
                    "<td>" + naturalsel + "</td>" +
                    "<td>" + ruleshtml + "</td>" +
                    "<td>" + demohtml + "</td>" +
                "</tr>");
        }
    });
    return output;
}

// Graphical 'fancy' button support code
// -------------------------------------
$(document).ready(function () {
    // Turn all buttons into fancy buttons
    var buttons = $("input.makefancy");
    if (buttons.length) {
        for (var i in buttons.get()) {
            makeButton(buttons[i]);
        }
    }
    
    // Handle a click on a fancy button
    $(".fancy_button .fancy_button_left, " +
            ".fancy_button .fancy_button_middle, " +
            ".fancy_button .fancy_button_right").click(function () {
        $(this).siblings("input.makefancy").get(0).click();
    });
});

// Turn the supplied button into a fancy button
function makeButton(button) {
    var buttontext = $(button).attr("value");
    var buttonid = $(button).attr("id");
    var fancyid = (buttonid) ? " id='fancy_" + buttonid + "' " : " ";
    
    $(button).hide();
    $(button).wrap($("<div" + fancyid + "class='fancy_button'></div>"));
    $(button)
        .after("<div class='fancy_button_right'></div>")
        .after("<div class='fancy_button_middle'><span>" + buttontext + "</span></div>")
        .after("<div class='fancy_button_left'></div>");
}

	/* Handle the hiding and showing of the login controls */

	// We turn the collapsed, clickable login area on here,
	// so it degrades gracefully.. we don't want this to show
	// if we're showing the login stuff in <noscript>
	//$("#userLoginCollapsed").show();

	$("#userLoginCollapsed").click(function () {
		$(this).hide();
    	$("#userLoginExpanded").show();
	});

	$("#userLoginExpanded a").click(function () {
		$("#userLoginExpanded").hide();
		$("#userLoginCollapsed").show();
	});
	/* End hiding and showing login controls */


	/*
		Handle blanking and defaulting of prompt text in input fields.

		NOTE: the password prompt is a dummy, so that the prompt text
		can be readable. Otherwise having it in a password
		type field would render it unreadable. So, when
		the prompt field gains the focus, we hide it, reveal
		the real password field, and give it focus.

	*/

	$("#loginForm #loginUsername").focus(function() {
		if ($(this).val() == "User Name")
		{
			$(this).val("");
		}
	});

	$("#loginForm #loginUsername").blur(function() {
		if ($(this).val() == "")
		{
			$(this).val("User Name");
		}
	});

	$("#loginForm #passwordPrompt").focus(function() {
        /*
		if ($("#loginForm #password").val() == "Password")
		{
			$("#loginForm #password").val("");
		}
       */
		$("#loginForm #password").show().focus();
		$(this).hide();
	});

	$("#loginForm #password").blur(function() {
		if ($(this).val() == "")
		{
			$("#loginForm #passwordPrompt").show();
			$(this).hide();
			//$("#loginForm #password").val("Password");
		}
	});
	
	    // Validation for MyHome login form
	    $("#loginForm").submit(function () {
	        return validateLoginForm();
	    });

	
	
	// Validation function for MyHome login form
	function validateLoginForm() {
	    var failFlag = false;
	    $("#loginForm input.required").each(function () {
	        if ($(this).val() == "" || $(this).val() == "User Name") {
	            if ($(".error[for='" + this.id + "']").length == 0){
	                $("<label for='" + this.id + "' class='error'>This field is required.</label>").insertAfter(this).hide().slideDown();
	            }
	            failFlag = true;
	        } else {
	            $(".error[for='" + this.id + "']").slideUp();
	            $(".error[for='" + this.id + "']").remove();
	        }
	    });
	    return !failFlag;
}
