var ieResize;

function getWindowHeight() {
  var h;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    h = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    h = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    h = document.body.clientHeight;
  }
  return h;
}

function getWindowWidth() {
  var w;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    w = window.innerWidth;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    w = document.documentElement.clientWidth;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    w = document.body.clientWidth;
  }
  return w;
}

function roundCorners() {
    $('#headernav ul').corner("12px");
    $('#toctitle').corner("tl 6px");
    $('#mt_head').corner("tl 12px");
    $('#mh_pagenav').corner("10px");
    $('#mf_pagenav').corner("10px");
    $('#supports .sp_head').corner("tr 12px");
    $('.button1').corner("9px");
    // ETR: This causes an error in IE:
    //$('.button2').corner("9px");
    $('.button3').corner("9px");
    $('.buttonag').corner("9px");
}

function pngFix() {
    $('img[@src$=.png]').pngfix();
}

function toggleTOC() {
    $('body').toggleClass("tocopen");
    $('#toctitle').corner("tl 6px");
    doLayoutResize();
    var tocopen = $.cookie('tocopen');
    if( tocopen == null )
        $.cookie("tocopen","true");
    else
        $.cookie("tocopen",null);
}

function keepTocOpen() {
    var tocopen = $.cookie('tocopen');
    if( tocopen == "true" ) {
      $('body').toggleClass("tocopen");
      $('#toctitle').corner("tl 6px");
      doLayoutResize();
    }
}

function openSupport(snum, level) {
    if (!level) level = getLevelCookie();
    setLevelCookie( level );
    // Close any open support item
    closeSupport();
    // Select related stop and think icon
    imageSwap($("#" + snum + "_a").children('img').get(0), 's');
    // Make selected item visible
    var srcID = snum + "_" + level;
    $('#'+srcID).show();
    // Show supports column
    $('body').addClass("suppopen");
    // Round corners for button/box items
    $('#'+srcID+' .sp_head').corner("tr 12px");
    $('#'+srcID+' .sp_levels').corner("10px");
    // ETR: This causes an error in IE:
    //$('#'+srcID+' .button2').corner("9px");
    $('#'+srcID+' .coachbar').corner("9px");
    // Update page layout
    // ETR: trying to get icons to go to the right places
    positionIcons();
}


function setLevelCookie( level ) {
    // Set updated level cookie
    $.cookie('book_level', level, {path: '/'});
}

function getLevelCookie() {
    // Get level from cookie, or default of level 1
    var level = null;
    level = $.cookie('book_level');
    if (level == null) {
        level = '1';
    }
    return level;
}

function closeSupport( textShow ) {
    // Unselect all stop and think icons
    $('.sticon').each(function() {
        imageSwap(this);
    });
    // Close feedback window
    closeFeedback();
    // Close support pane
    $('.sp_content').hide();
    $('.pulldown').hide();
    $('.hideText').show();
    $('.highlightText').toggleClass("highlightText");
    $('.highlightText').hide();
    $('.showButton').text( textShow );
    $('body').removeClass("suppopen");
    // ETR: trying to get icons to go to the right places
    positionIcons();
}

function literaryDevices() {
    $('.ld').mouseover(function() { highlightDevice(this,'on'); } );
    $('.ld').mouseout(function() { highlightDevice(this,'off'); } );
    $('.ld').focus(function() { highlightDevice(this,'on'); } );
    $('.ld').blur(function() { highlightDevice(this,'off'); } );
}

function highlightDevice(currNode, state) {
    var targetID = $(currNode).attr("name");
    if (state == 'on') {
        $('#a_' + targetID).addClass("ld_highlight");
    } else {
        $('#a_' + targetID).removeClass("ld_highlight");
    }
}

function openFeedback(srcID) {
    // Hide any open feedback item
    closeFeedback();
    // Show selected feedback
    $('body.suppopen').each(function() {
        $('#'+srcID).show();
        // Position feedback box
        positionFeedback(srcID);
        // Round corners for button/box items
        $('#'+srcID+' .button3').corner("9px");
        $('#'+srcID+' .buttonag').corner("9px");
        $('#'+srcID+' .fb_inner').corner("10px");
    });
}

function closeFeedback() {
    $('.feedback:visible').hide();
}

function positionFeedback() {
    var siND = null;
    var fbID = "";

    // Only execute on open support column
    $('body.suppopen').each(function() {
        // Find visible support node
        $('.sp_inner:visible').each(function() {
            siND = this;
        });

        // Find visible feedback node
        $('.feedback:visible').each(function(){
            fbID = this.id;
        });

        // Position feedback box on top of support box
        if ((siND != null) && (fbID != "")) {
            //var sc = targetCoordsLayout(siND);
            //$('#'+fbID).css("top", sc.targetTop + 25 + "px");
            //$('#'+fbID).css("left", sc.targetLeft + 10 + "px");
            var sc = targetCoordsLayout(document.getElementById("supports"));
            $('#'+fbID).css("top", sc.targetTop + 75 + "px");
            $('#'+fbID).css("left", sc.targetLeft + 17 + "px");
        }
    });
}

function captionSize() {
    $('.imgcaption').each(function() {
        $(this).width($(this).prev("img").width()-6);
    });
    $('.nocaption').each(function() {
        $(this).width($(this).prev("img").width());
    });

    // Hack for clearing above images in FF
    if ($.browser.mozilla) {
        $('.imgleft, .imgright, .imgcenter').each(function() {
            $(this).before('<div class="ffimgclear"></div>');
        });
    }
}

function positionIcons() {
    // Reset location array
    var i = 0;
    var locIcons = new Array();

    // Find each icon
    $('.icons').each(function() {
        // Update flag/reset location
        var updateLoc = false;
        $(this).css("top", "auto");
        // Find top coord
        var tempTop = this.offsetTop;
        //Check to see if this interferes/overlaps with the previous button
        if (i > 0) {
            if (tempTop <= (locIcons[i-1] + 22)) {
                // Move button down a bit below previous one
                tempTop = locIcons[i-1] + 23;
                updateLoc = true;
            }
        }
        // Align button on page
        if (updateLoc) {
            $(this).css("top", tempTop + "px");
        }
        // Save button location
        locIcons[i] = tempTop;
        i++;
    });
}

function doLayoutResize() {
    positionIcons();
    //positionFeedback();
    resizeFeedback();
    setTimeout('clearTimeout(ieResize)', 50);
}

$(window).ready(function() {
    $('.figlang').hide();
    keepTocOpen();
    captionSize();
    positionIcons();
    literaryDevices();
    $('#toctaba').attr("href", "javascript:toggleTOC();");
    randomizeSubstMenus();
    roundCorners();
});

$(window).resize(function() {
    if (ltIE7) {
        clearTimeout(ieResize);
        ieResize = setTimeout(doLayoutResize, 200);
    } else {
        doLayoutResize();
    }
});


function openFeedback2(srcID) {
    $('#'+srcID).show();
    $('#'+srcID).css("top", "80px");
    $('#'+srcID).css("right", "35px");
    $('#'+srcID).css("z-index", "5");
    $('#'+srcID+' .button3').corner("9px");
    $('#'+srcID+' .buttonag').corner("9px");
    $('#'+srcID+' .fb_inner').corner("10px");
    resizeFeedback();
}

function resizeFeedback() {
    // Find height of support column
    var siObj = $('.sp_content:visible .sp_inner').get(0);
    var fbObj = $('.feedback:visible').get(0);

    if ( (siObj != null) && (fbObj != null)) {
        var fbID  = fbObj.id;

		// Reset size
		$('#'+fbID+' .f_wrapper').css("height", "auto");
		$('#'+fbID+' .f_wrapper').removeClass("f_scroll");

        // Get content height
        var siH = siObj.offsetHeight;
        var fbH = fbObj.offsetHeight;

        // Shorten and add scrolling if needed
        if (fbH >= (siH)) {
            $('#'+fbID+' .f_wrapper').css("height", (siH-42)+"px");
            $('#'+fbID+' .f_wrapper').addClass("f_scroll");
        }
    }
}

function toggleSubs(ids) {
    var idlist = ids.split( "," );
    for( i=0; i<idlist.length; i++ ) {
        if( idlist[i] != "" ) {
            $("#"+idlist[i]).addClass("hideText");
            $("#"+idlist[i]).toggle();
            var menu = document.getElementById( idlist[i]+"-realmenu" );
            if( menu == null ) {
                menu = $( "<select>" + $("#"+idlist[i]+"-substmenu").html() + "</select>" );
                menu.attr( "class", "pulldown" );
                menu.attr( "id", idlist[i]+"-realmenu" );
                menu.get(0).selectedIndex = 0;
                $("#"+idlist[i]).after( menu );
            } else {
                $( menu ).remove();
            }
        }
    }
    positionIcons();
}

function toggleHilightRegion(ids) {
    var idlist = ids.split( "," );
    for( i=0; i<idlist.length; i++ ) {
        if( idlist[i] != "" ) {
            $("#"+idlist[i]).toggleClass("highlightText");
        }
    }
}

function toggleButtonName(a,name1,name2) {
    if( $(a).text() == name1 )
        $(a).text(name2);
    else
        $(a).text(name1);
}

function setChoiceFeedback(fbText,fbVal,path,sid,choice,language,debug) {
    var agentString = "AGENT2,"+path+","+sid+","+choice+","+language;
    if(debug!=null && debug=='true')
        alert( "fbText: " + fbText +
            "\nfbVal: " + fbVal +
            "\npath: " + path +
            "\nsid: " + sid +
            "\nchoice: " + choice +
            "\nlanguage: " + language +
            "\nagentString: " + agentString );
    $('#choice-feedback-text').text(fbText);
    if(fbVal=='true') {
		if( language == 'es' )
			$('#choice-feedback-title').text("Muy bien!");
		else
			$('#choice-feedback-title').text('Good Work!');
        $('#choice-feedback-tryagain').hide();
    } else {
		if( language == 'es' )
			$('#choice-feedback-title').text('Revise su trabajo');
		else
			$('#choice-feedback-title').text('Check Your Work');
        $('#choice-feedback-tryagain').show();
    }
    $('#choice-feedback-listen-link').attr('onclick',"return runAgent('"+sid+"_"+choice+"','"+agentString+"')");
    $('#choice-feedback-listen-link-debug').attr('href',agentString);
}

function setSubstitutionsFeedback( ids, themeName, language ) {
    var idlist = ids.split( "," );
	if( ! getCompletenessOfSubstMenus( idlist, language )) return;
    var themeNum = 1;
    var theme = "UNDEFINED";
    for( i=1; i<=7; i++ ) {
        var radio = $('#'+themeName+'-'+i);
        if( radio != null && radio.attr('checked') != null ) {
            themeNum = i;
            theme = radio.next().text();
        }
    }
	var isCorrect = getCorrectnessOfSubstMenus( idlist, themeNum );
    var idSelector = "";
    for( var i=0; i<idlist.length; i++ ) {
        idSelector = idSelector + "#" + idlist[i] + ",";
    }
    var passage = "";
    $( idSelector ).parent().each(
        function(i) {
			passage = passage + getParaTextForSubstMenus( this, themeNum );
		}
    );
    $('#substitutions-feedback-passage').html( passage );
    if( isCorrect ) {
		if( language == 'es' ) {
			$('#substitutions-feedback-title').text('Muy bien!');
			$('#substitutions-feedback-text').text(
			     'Todos los cambios se ajustan a la eleccion "' + theme + '"' );
		} else {
			$('#substitutions-feedback-title').text('Good Work!');
			$('#substitutions-feedback-text').text(
				 'All your changes fit the choice "' + theme + '"' );
		}
        $('#substitutions-feedback-tryagain').hide();
    } else {
		if( language == 'es' ) {
			$('#substitutions-feedback-title').text('Revise su trabajo');
			$('#substitutions-feedback-text').text(
					   'Sus cambios en el texto no parecen encajar su eleccion '
					   + '"' + theme + '" Compruebe debajo de sus selecciones y vuelve a intentarlo.' );
		} else {
			$('#substitutions-feedback-title').text('Check Your Work');
			$('#substitutions-feedback-text').text(
					   'Some of your changes to the text do not seem to fit your choice, '
					   + 'which was "' + theme + '." Check your selections '
					   + 'below and try again.' );
		}
        $('#substitutions-feedback-tryagain').show();
    }
    $('#substitutions-feedback-table').html( getTableForSubstMenus( idlist, language ));
    openFeedback2('substitutions-feedback');
}


function getCompletenessOfSubstMenus( idlist, language ) {
    for( i=0; i<idlist.length; i++ ) {
        if( idlist[i] != "" ) {
            var select = document.getElementById(idlist[i]+"-realmenu");
            if( select == null ) {
				if( language == 'es' ) {
					alert( "Usted no se ha hecho todavia.\n"
						   + "Usted debe elegir suplentes texto primero." );
				} else {
					alert( "Oops! You aren't done yet!\n"
						   + "Click the 'show' button and make your alternate "
						   + "text choices before clicking 'done'." );
				}
				return false;
			} else {
				var option = select.options[ select.selectedIndex ];
				if( option.value == 0 ) {
					if( language == 'es' ) {
						alert( "Usted no se ha hecho todavia.\n"
							   + "Usted debe elegir suplentes texto primero." );
					} else {
						alert( "Oops! You aren't done yet!\n"
							   + "Make sure you have selected all your alternate "
							   + "text choices before clicking 'done'." );
					}
					return false;
				}
			}
        }
    }
	return true;
}


function getCorrectnessOfSubstMenus( idlist, themeNum ) {
    for( i=0; i<idlist.length; i++ ) {
        if( idlist[i] != "" ) {
            var select = document.getElementById(idlist[i]+"-realmenu");
            if( select != null ) {
				var option = select.options[select.selectedIndex];
				if( option.value != themeNum )
					return false;
			}
        }
    }
	return true;
}


function getParaTextForSubstMenus( elem, themeNum ) {
    var text = "";
    for( var i=0; i<elem.childNodes.length; i++ ) {
        var node = elem.childNodes[i];
	var elemNode = ( window.Node ) ? Node.ELEMENT_NODE : 1;
        if( node.nodeType == elemNode ) {
            if( node.nodeName.toLowerCase() == "span"
                && node.getAttribute( "class" ) != null
		&& node.getAttribute( "class" ).indexOf( "hideText" ) > -1 ) {
            } else if( node.nodeName.toLowerCase() == "select" ) {
		var option = node.options[ node.selectedIndex ];
		var bgcolor = ( option.value != themeNum ) ? "lightsalmon" : "lightgreen";
		text += " <span style='background-color:" + bgcolor + "'>"
		    + $(option).text()
		    + "</span> ";
            } else {
                text = text + getParaTextForSubstMenus( node );
            }
	} else {
            text = text + node.nodeValue;
        }
    }
    return text;
}

function getTableForSubstMenus( idlist, language ) {
    var table = "<table class='fb_table'><thead><tr>";
	if( language == 'es' ) {
		table = table
			+ "<th class='fb_th'>Original de las palabras</th>"
			+ "<th class='fb_th'>Sus palabras</th>";
	} else {
		table = table
			+ "<th class='fb_th'>Original Words</th>"
			+ "<th class='fb_th'>Your New Words</th>";
	}
	table = table + "</tr></thead><tbody>\n";
    for( i=0; i<idlist.length; i++ ) {
        if( idlist[i] != "" ) {
            var origText = $('#'+idlist[i]).text();
            var select = document.getElementById(idlist[i]+"-realmenu");
            if( select != null ) {
				var option = select.options[select.selectedIndex];
				var choiceText = $(option).text();
				table = table + "<tr><td class='fb_td'>" + origText
					+ "</td><td class='fb_td'>" + choiceText + "</td></tr>";
			}
        }
    }
    table = table + "</tbody></table>\n";
	return table;
}


function randomizeSubstMenus() {
    $(".substitutionMenu").each( function(i) {
        var shifts = Math.floor( 3 * Math.random() );
        for( var i=0; i<shifts; i++ ) {
            $(this).append( $(this).children("option:first").remove() );
        }
        var option = $("<option>");
        option.attr("value","0");
        option.attr("selected","selected");
        option.text("-----");
        $(this).prepend( option );
    });
}
