/**
 * adds trim method to strings
 *
 * @param {String} delim A list of characters to remove from beginning and end
 *				         of the current string; default is whitespace
 */
String.prototype.trim = function(delim) {
	return this.replace(new RegExp("^[\\s" + delim + "]+"),'').replace(new RegExp("[\\s" + delim + "]+$"), '');
}

/***
 * Sets textbox input state to blur/focus styles
 *
 * @param	o		DOMObject	The input object to style
 * @param	action	string		The action to style
 */
function formatInput(o, action) {
	switch(action) {
		case "blur":
			o.className = "blur";
			break;
		case "focus":
			o.className = "focus";
			break;
		default:
			break;
	}
}

/**
 * Provides generic form validation.
 *
 * Usage:
 * 1. Add to form: onsubmit="return(fmValidate(this))"
 * 2. Add required="true" attribute to desired inputs
 * 2a. Add validate="email" to input that needs email format verification
 *
 */
function fmValidate(theForm) {
	var hlColor = "#fc3";
	var hlMark = "&raquo;"
    var isValid = true;
	
	var els = theForm.elements;
    var emailRegex = /^[A-Za-z0-9\_\-\.]+@([A-Za-z0-9\-]+\.)+[A-Za-z]{2,}$/;
	var firstBad = false;
    for(var i=0; i < els.length; i++) {
		var el = els[i];
		if(el.getAttribute("required") == "true") {
	        if(el.value == "") {
	            el.style.background = hlColor;
	            isValid = false;
				fmToggleMark(el.id, true);
				if(!firstBad) {
					el.focus();
					firstBad = true;
				}
	        } else {
	            el.style.background = "none";
				fmToggleMark(el.id, false);
	        }				
		}
		if(el.getAttribute("validate") == "email" && !emailRegex.test(el.value)) {
            el.style.background = hlColor;
            isValid = false;
			fmToggleMark(el.id, true);
		}
    }
    
    if(!isValid) alert("You need to fill in the required fields,\nwhich are marked in yellow.");
    return isValid;
}

/**
 * Toggles the error chevron on form inputs.
 *
 */
function fmToggleMark(inputId, turnOn) {
	var mk = document.getElementById(inputId + "_Err");
	if(!turnOn && mk != null) {
		mk.parentNode.removeChild(mk);
	} else if(turnOn && mk == null){
		mk = document.createElement("span");
		mk.id = inputId + "_Err";
		mk.className = "mark";
		mk.appendChild(document.createTextNode("»"));
		var inp = document.getElementById(inputId);
		inp.parentNode.insertBefore(mk, inp);
	}
}


function getElementsByClassName(node, classname)
{
    var a = [];
    var re = new RegExp('\\b' + classname + '\\b');
    var els = node.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
        if(re.test(els[i].className))a.push(els[i]);
    return a;
}

function flipPanel(caller, panelId) {
	var panels = getElementsByClassName(document, $(panelId).className);
	for(var i=0,l=panels.length; i<l; i++) {
		if(panels[i].id == panelId) Element.show(panels[i]);
		else Element.hide(panels[i]);
	}
	
	var links = getElementsByClassName(document, caller.className);
	for(var i=0,l=links.length; i<l; i++) {
		if(links[i] == caller) Element.addClassName(caller, 'selected');
		else Element.removeClassName(links[i], 'selected');
	}
	
}

var gRotatePanelsPid = 0;
function rotatePanels(panelClass, panelContainer, selectedIndex, timeout) {

	var ACTIVE_CLASS_NAME = 'activePanel';
	
	// kill any lingering timers
   //clearTimeout(gRotatePanelsPid);

    // set defaults
    if(!selectedIndex) selectedIndex = 0;
    if(!timeout) timeout = 5000;
    
    // get DOMs
    var domContainer = $(panelContainer);
	var domPanels = getElementsByClassName(domContainer, panelClass);
	var panelCount = domPanels.length;
    
    // determine next panel to show
    var nextIndex = (selectedIndex + 1) % panelCount;
    var activeIndex = 0;
	
	// hide all panels
	for(var i=0; i<panelCount; i++) {
	    if(Element.hasClassName(domPanels[i], ACTIVE_CLASS_NAME)) {
	        activeIndex = i;        
	        break;
	    }
	}
	
	// console.debug("switching to panel: " + nextIndex);

	// hide active panel
    //Element.removeClassName(domPanels[activeIndex], ACTIVE_CLASS_NAME);
    
	// show new one
	Element.addClassName(domPanels[selectedIndex], ACTIVE_CLASS_NAME);
	
	// schedule next rotation
	//gRotatePanelsPid = setTimeout('rotatePanels("' + panelClass + '","' + panelContainer + '",' + nextIndex + ',' + timeout + ')', timeout);
	
	return true;
    
}




function switchContentImageTheme(themeName) {

	if(!themeName) return false;
	
	// define the segment in the image src path that is the skin/theme name
	// remember that this is 0-indexed
	// current expected path: /themes/splunk_com/img/skins/white
	var replaceSegmentIndex = 4;

	// define the containing object from which to search
	var container = $('wrapper');

	// define the classname of images that are to be switched
	var skinnableClass = 'skinnable';

	// pull out all the matching images and do replace
	var images = container.getElementsByTagName('img');
	var imagePath = '';
	var re = new RegExp('\\b' + skinnableClass + '\\b');
	for(var i=0,l=images.length; i<l; i++) {
		
		imagePath = images[i].src;

		//console.debug("checking image: " + imagePath);
		
		// check if image has src, and is of proper class
		if(!images[i].src || !re.test(images[i].className)) continue;
		
		// strip the absolute path
		if(imagePath.substring(0,5) == 'http:' || imagePath.substring(0,6) == 'https:') {
			imagePath = imagePath.substring(imagePath.indexOf('/',8) + 1);
		}

		// switch out the skin name
		imagePath = imagePath.trim('/').split('/');
		imagePath[replaceSegmentIndex] = themeName;
		
		// set the image src with new path
		images[i].src = '/' + imagePath.join('/');

		//console.debug("switched -> " + images[i].src);
	}
		
	// check to see which theme we're in
	if (themeName == 'white' || themeName == null){
		// include black h2's
		var h2color			= '#111111';
		var h2background	= '#ffffff';
		
	} else {
		// include white h2's
		var h2color			= '#ffffff';
		var h2background	= '#181818';
	}


	
//	var sifrresult = sIFR.replace(
//		myriad, 
//		{selector: 'h2, h3,.toc2',
//		wmode: 'transparent',
//		css: [
//			'.sIFR-root { text-align: left; font-weight: normal; color:'+ h2color + '; background-color: '+ h2background + ';}'
//			,'a { text-decoration: none }'
//			,'a:link { color: #0a78a0 }'
//			,'a:hover { color: #0a78a0 }'
//			]
//		}
//	);


	return true;

}

function switchGlobalTheme(themeName, days) {
	chooseStyle(themeName, days);
	switchContentImageTheme(themeName);
	return true;
}


function openDemo2(demoname){
		
	// define where we'll go
	var	gotoUrl = '';
	
	// set width 
	var width = 800;
	var height = 650;
	

	if (!demoname) return false;
	
	// see who they're trying to get
	if (demoname == 'chris'){
		gotoUrl = '/web_assets/screencastdemos/chris_mcdaniel/reardendemo.html';
		width = 875;
		height = 640;
	}
	if (demoname == 'corey'){
		gotoUrl = '/web_assets/screencastdemos/corey_shields/corey2.html';
		width = 1000;
		height = 550;
	}
	if (demoname == 'brent'){
		gotoUrl = '/web_assets/screencastdemos/brent_chapman/brentdemo.html';
		width = 875;
		height = 640;
	}
	if (demoname == 'matthew'){
		gotoUrl = '/web_assets/screencastdemos/matthew_zeier/mozilla.html';
		width = 900;
		height = 655;
	}
	
	if (demoname == 'steve'){
		gotoUrl = '/web_assets/screencastdemos/steve_loyd/index.html';
		width = 950;
		height = 650;
	}
	
	if (demoname == 'sneakpeekQT1'){
		gotoUrl = '/web_assets/video/movie1.html';
		width = 660;
		height = 390;
	}
	
	if (demoname == 'sneakpeekQT2'){
		gotoUrl = '/web_assets/video/movie2.html';
		width = 660;
		height = 390;
	}
	
	if (demoname == 'sneakpeekQT3'){
		gotoUrl = '/web_assets/video/movie3.html';
		width = 660;
		height = 390;
	}
	
	if (demoname == 'sneakpeekQT4'){
		gotoUrl = '/web_assets/video/movie4.html';
		width = 660;
		height = 390;
	}
	
	window.open(gotoUrl,'blank','toolbar=no,width=' + width + ',height=' + height);
	
	return false;
}


function openVideo(url,width,height){
		
	// define where we'll go
	var	gotoUrl = '/web_assets/' + url;
	


	if (!url) return false;
	
	
	window.open(gotoUrl,'blank','toolbar=no,width=' + width + ',height=' + height);
	
	return false;
}

function showhide(layer_ref) {

	if (editor_nav_state == 'block') {
		editor_nav_state = 'none';
	}
	else {
		editor_nav_state = 'block';
	}
	if (document.all) { //IS IE 4 or 5 (or 6 beta)
		eval( "document.all." + layer_ref + ".style.display = editor_nav_state");
	}
	if (document.layers) { //IS NETSCAPE 4 or below
		document.layers[layer_ref].display = editor_nav_state;
	}
	if (document.getElementById &&!document.all) {
		hza = document.getElementById(layer_ref);
		hza.style.display = editor_nav_state;
	}
}