if (typeof WILEY == "undefined") {var WILEY = {};}
if (typeof WILEY.dummies == "undefined") {WILEY.dummies = {};}
if (typeof WILEY.dummies.util == "undefined") {WILEY.dummies.util = {};}

//-------------------------- INITIALIZATION FUNCTIONS ----------------------------------

_initialize = function(){
	// I. TOPNAV
	// if the page has a topnav and javascript is available, then show enhancements
	if($("expanding-nav")){	
		//attach ids to submenus
		$$("ul.submenu").each(function(item,index) { 
			item.id = "submenu_"+index;
		});

		//turn on dropdown buttons
		$$("ul.menu li a").each(function(menuAnchor) { 
			menuAnchor.style.paddingRight = "35px";
		});
		$$("#topnav .expander").each(function(expander){
			expander.style.display = "inline";
		});	
	
		_attachListeners();
	}
	//II. LIGHTBOX
	$$('#wrapper a[rel="lightbox"]').each(function(lbxAnchor, index){
	    Event.observe(lbxAnchor,'click', function(e){
	        _showLightbox(lbxAnchor);
	        Event.stop(e); //return false
	    });	
	});
    //III. Open external links in articles in a new window
    if ($$(".article-content")) {
        this.check = function(obj){
            var href = obj.href.toLowerCase();
            return (href.indexOf("http://")!=-1 && href.indexOf(hostname)==-1) ? true : false;              
        };
        this.set = function(obj){
            obj.target = "_blank";
            obj.className = "external";
        };
        var hostname = window.location.hostname;
        hostname = hostname.replace("www.","").toLowerCase();
        $$(".article-content a").each(function(link) {
            if (check(link)) {
                set(link);
            }
        });
    }
}

Event.observe(window, 'load', _initialize, false);

//-------------------------- TOPNAV ----------------------------------
_closeOpenMenu = function(){
	$(activeMenuId).style.display = "none";
}

//to force only 1 menu open at a time
var activeMenuId="";

//Set up onclicks, onmouseovers, etc
_attachListeners = function(){
	//assign event handler to expander passing in corresponding submenu item id
	$$(".expander").each(function(expander,index) { 
	
		Event.observe(expander,'click', function(e){
			if($('submenu_'+index).style.display == "none"){
				//see if a menu is already open by checking a manually created variable - if it doesn't match the current menuButton you clicked, close the previously clicked.
				if(activeMenuId!="" && activeMenuId!='submenu_'+index){
					_closeOpenMenu();
					activeMenuId = "";
				}
				Effect.Appear('submenu_'+index, { duration: 0.2 });
				_toggleOpacity("show", expander.parentNode);
				activeMenuId = 'submenu_'+index;
			} else {
				Effect.Fade('submenu_'+index, { duration: 0.2 });
				_toggleOpacity("hide", expander.parentNode);	
				activeMenuId = "";
			}
			Event.stop(e); //return false
		});			
	});

	Event.observe(document.body, 'click', _bodyClick);   
}

/*This fixes an IE bug where the submenu was appearing under the text of another menu item when the topnav wrapped
  */
_toggleOpacity = function(state, liItem){
	if(state == "hide"){
		liItem.style.zIndex = "0";
	} else {
		liItem.style.zIndex = "200";
	}
}

// to close any open submenus on bodyclick
_bodyClick = function(event){
	if( !$(event.element()).up('.menu') && activeMenuId != "" ){
		_closeOpenMenu();
		var liClicked = $(activeMenuId).parentNode;
		_toggleOpacity("hide",liClicked);	
	}
}

// resize the container nav in order to show the submenus. Need to do this because of the overflow needed for carousel
_resizeNav = function(){
	var submenuHeights = new Array;

	//get largest submenu height
	$$('.submenu').each(function(submenuObj,index) { 
		submenuHeights.push(submenuObj.getHeight());
	});
	var largestHeight = Math.max.apply(Math,submenuHeights);
	
	//set container to that height
	$$('#topnav .container')[0].style.height = largestHeight+40+"px";
}

//if contents of submenu > 35char then cut off and replace with ellipsis
_cutOffSubmenuTxt = function(){
	var tmp;
	
	$$("ul.submenu li a").each(function(item) { 
		if(item.innerHTML.length > 35){
			tmp = item.innerHTML.substr(0,32).concat('...');
			item.innerHTML = tmp;
		}	
	});	
}

//-------------------------- / END TOPNAV ----------------------------------

//-------------------------- MISC UTILITY FUNCTIONS ----------------------------------
WILEY.dummies.util.openMe = function(id) {
    new Effect.Appear(id,{duration:.3});
}
WILEY.dummies.util.closeMe = function(id) {
    new Effect.Fade(id,{duration:.3});   
}
WILEY.dummies.util.goToURL = function(destination) {
    if (destination) location.href = destination;
}

//GENERIC MODAL ALERT
WILEY.dummies.util.modalAlert = function(title, content, height){
    var modalContents = "<div class=\"titlebar\"><a href=\"#\" onclick=\"return false;\">"
                + "<img class=\"closeModal\" src=\"http://media.wiley.com/assets/1547/15/icon_modal-close.gif\" alt=\"close\" /></a></div>" 
                + "<div class=\"title\">"+title+"<\/div><div>"+ content +"<\/div>";
    
	Control.Window.open(modalContents,{
    	width: 350,
		height: height,
		fade: true,
		closeOnClick: true,
		className: 'modal-alert'
	});
}

_showLightbox = function(lbxAnchor){
    var lbxContents = "<div class=\"titlebar\"><a href=\"#\" onclick=\"return false;\">"
                    + "<img class=\"closeModal\" src=\"http://media.wiley.com/assets/1547/15/icon_modal-close.gif\" alt=\"close\" /></a></div>" 
                    + "<div class=\"title\">"+lbxAnchor.title+"</div><div><img src=\""+lbxAnchor.href+"\" alt=\"\" \/></div>";
    
    //need width to display correctly in IE
    var dim = lbxAnchor.href.toQueryParams();
	var dimHeight = parseInt(dim.h) + 90;
	var dimWidth = parseInt(dim.w) + 40;    
                    
    Control.Window.open(lbxContents,{  
        className: 'lightbox',
        fade: true,  
        height: dimHeight,
        width: dimWidth,
        closeOnClick: true  
    });
}

//Title page functions
loadLargeCover = function(coverImagePath,coverImageHeight,coverImageWidth) {         
    if ($('large-cover-image').childNodes.length > 0) {
        WILEY.dummies.util.openMe('large-cover');
    } else {
        var largeImage = document.createElement('img');
        largeImage.src = coverImagePath;
        largeImage.width = coverImageWidth;
        largeImage.height = coverImageHeight;
        $("large-cover-image").appendChild(largeImage);
        WILEY.dummies.util.openMe('large-cover');
    }
}

//-------------------------- VALIDATION FUNCTIONS ----------------------------------
WILEY.dummies.util.FormValidation = {
    validText: function(fieldName,fieldRequired,fieldMaxLength,fieldValue) {
    	var textErrors = "";
    	if (fieldRequired && ((fieldValue == null) || (fieldValue == ""))) {
    		textErrors += '<li><span>'+fieldName + ' is empty<\/span><\/li>';
    	}
    	return textErrors;
    },

    validNumber: function(fieldName,fieldRequired,fieldMaxLength,fieldValue) {
    	var numberErrors = "";
    	if (fieldRequired && ((fieldValue == null) || (fieldValue == ""))) {
    		numberErrors += '<li><span>'+fieldName + ' is empty<\/span><\/li>';
    	}
        return numberErrors;
    },

    validEmail: function(fieldName,fieldRequired,fieldMaxLength,fieldValue) {
        var emailErrors = WILEY.dummies.util.FormValidation.validText(fieldName,fieldRequired,fieldMaxLength,fieldValue);
        if (fieldValue!=null && fieldValue!="") {
            if (fieldValue.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) == -1) {
                emailErrors += '<li><span>'+fieldName + ' is invalid<\/span><\/li>';
            }
        }
        return emailErrors;
    }
};   

// Dynamically goes through required values and validates. See EMF form for sample usage
WILEY.dummies.util.validateForm = function(formId){
    var errors = "";
    
    $$("form#"+formId+" .required.text").each(function(requiredField) { 
        errors += WILEY.dummies.util.FormValidation.validText(requiredField.title,true,200,requiredField.value);
    });
    
    $$("form#"+formId+" .required.email").each(function(requiredField) { 
        errors += WILEY.dummies.util.FormValidation.validEmail(requiredField.title,true,100,requiredField.value);
    });
    
   if (errors != "") {
        var title = "Please fix the following errors";
        errors = "<ul>"+errors+"<\/ul>";
        WILEY.dummies.util.modalAlert(title, errors, '200');
        return;
    }
    $(formId).submit();
}
