/* global.js */

var reddit = null;  //initial reddit variable for 'programming' links

function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') 
    {
        window.onload = func;
    } 
    else 
    {
        window.onload = function() 
        {
            oldonload();
            func();
        };
    }
}

/* begin js url validity checker */

function checkUrlValidity() {
    var theUrl = document.location.href;
	
	//un-namespaced wiki article link pattern
    var pattern = /(\w+):\/\/(.*)(special)\?(.*)/; // ([\w._-]+)\/(\S*)
    var urlMatch = theUrl.match(pattern);
    
    if(urlMatch != null) {
		displayError("wikiLinkNoNS");
    } 
    
}
addLoadEvent(checkUrlValidity);

function displayError(type) {
	var message;
	
	// todo: take the common elements out so that they're not repeated
	switch(type) {
		case "wikiLinkNoNS":
		  message = ""+
		    "<div class=\"services errors\">"+
			"<h2>Webmonkey Has Moved!</h2><br/>"+
			"<p>Ooops! It looks like you just clicked on a link in a wiki article with no namespace.</p>"+
			"<p>All links in Webmonkey articles need to either be absolute (i.e.: [http://somesite.com/page.html]) or namespaced, relative links (i.e.: [[Tutorial:Code_Perl]]).</p>"+
			"<p>Try going back to the <a href=\"javascript:history.go(-1)\">previous page</a> and adding a namespace of Tutorial, Reference, or Codelibrary to the broken link.</p>"+
			"</div>"
			break;
		default:
		  message = ""+
		    "<div class=\"services errors\">"+
			"<h2>Webmonkey Has Moved!</h2><br/>"+
			"<p>Ooops! Webmonkey.com has moved, and the page you're requesting has moved along with it.</p>"+
			"<p>The entire Webmonkey website is now a wiki supported by MediaWiki, the open-source software platform originally created for Wikipedia.</p>"+
			"<p>We're moving all of the articles over from the old site, and either we haven't gotten to the one you're looking for yet or it's already been moved. Use the search bar in the upper right-hand corner of the page to locate your article's new home.</p>"+
			"<p>If it doesn't show up in the search results and you're dying to see it again, <a href=\"mailto:webmonkey@wired.com\">let us know about it</a> and recommend we move it to the top of the list.</p>"+
			"</div>"
		    break;
	}
	
	var theContent = $("the_content");
	if(theContent) {
		theContent.style.padding = "10px";
	    theContent.innerHTML = message;
	}
}

/* end url valilidty checker */

/* begin common cookie functions.  see http://techweb/javascript_commons/docs/cookies.html for documentation. */
/* Set cookie value */
function setCookie(name, value, escapeValue, expires, path, domain, secure) {

    var cookieToken = name + '=' + ((escapeValue) ?  escape(value) : value) + ((expires) ? '; expires=' + expires.toGMTString() : '') + ((path) ? '; path=' + path : '') + ((domain) ? '; domain=' + domain : '') + ((secure) ? '; secure' : '');
    document.cookie = cookieToken;

}

/* Get cookie value */
function getCookie(name) {
    var allCookies = document.cookie;
    
    var cookieName = name + "=";
    var start = allCookies.indexOf("; " + cookieName);
    
    if (start == -1) {
        start = allCookies.indexOf(cookieName);
        if (start != 0) return null;
    }
    else start += 2;
    
    var end = document.cookie.indexOf(";", start);
    if (end == -1) end = allCookies.length;
    
    return unescape(allCookies.substring(start + cookieName.length, end));
}

/* Delete a cookie */
function deleteCookie(name, path, domain) {
    var value = getCookie(name);
    if (value != null) document.cookie = name + '=' + ((path) ? '; path=' + path : '') + ((domain) ? '; domain=' + domain : '') + '; expires=Thu, 01-Jan-70 00:00:01 GMT';
    return value;
}

/* Test for cookie support */
function verifyCookieSafe() {
    setCookie('pingCookies', 'hello');
    if (getCookie('pingCookies')) return true;
    else return false;
}

/* end common cookie functions. */

/* begin text size widget */
function setActiveStyleSheet(title) {
  var i, a, main;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
      a.disabled = true;
      if(a.getAttribute("title") == title) a.disabled = false;
    }
  }
}

function getActiveStyleSheet() { 
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
	if (a.getAttribute("rel") != null) {
	    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
	}
  }
  return null;
}

function getPreferredStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1
       && a.getAttribute("rel").indexOf("alt") == -1
       && a.getAttribute("title")
       ) return a.getAttribute("title");
  }
  return null;
}

window.onunload = function(e) {
    var title = getActiveStyleSheet();
    //var expiration = new Date();
    //var expDuration = expiration.getTime() + (365*24*60*60*1000);
    //expiration.setTime(expDuration);
    setCookie("style", title, false, "", "/", "", false);
}

var textPref = getCookie("style");
var title = textPref ? textPref : getPreferredStyleSheet();
setActiveStyleSheet(title);

/* end text size widget */

// IE6 functions

// cache css bg images for IE6
if ( document.all )
{  
    try {
      document.execCommand("BackgroundImageCache", false, true);
    } catch(err) {}
}

// IE hover and Z-index fix for main navigation
startList = function() {
    if (document.all&&document.getElementById) {
        zCount = 100;
       if (document.getElementById("wm_nav") != null) {
           navRoot = document.getElementById("wm_nav");
           for (i=0; i<navRoot.childNodes.length; i++) {
             node = navRoot.childNodes[i];
             if (node.nodeName=="LI") {
                //node.style.zIndex = zCount;  /*this is screwing up something on ie6 navbar and removing it doesn't seem to hurt MHM*/
                zCount--;
                node.onmouseover=function() {
                    this.className+=" over";
                }
                node.onmouseout=function() {
                    this.className=this.className.replace(" over", "");
                }
             }
           }
       }
	   
	   if (document.getElementById("head_login_bar") != null) {
           navRoot = document.getElementById("head_login_bar");
           for (i=0; i<navRoot.childNodes.length; i++) {
             node = navRoot.childNodes[i];
             if (node.nodeName=="LI") {
                node.style.zIndex = zCount;
                zCount--;
                node.onmouseover=function() {
                    this.className+=" over";
                }
                node.onmouseout=function() {
                    this.className=this.className.replace(" over", "");
                }
             }
           }
       }
       if (document.getElementById("btn-edit-article") != null) {
           navRoot = document.getElementById("btn-edit-article");
           for (i=0; i<navRoot.childNodes.length; i++) {
             node = navRoot.childNodes[i];
             if (node.nodeName=="A") {
                node.style.zIndex = zCount;
                zCount--;
                node.onmouseover=function() {
                    this.className+=" over";
                }
                node.onmouseout=function() {
                    this.className=this.className.replace(" over", "");
                }
             }
           }
       }
       if (document.getElementById("btn-discuss") != null) {
           navRoot = document.getElementById("btn-discuss");
           for (i=0; i<navRoot.childNodes.length; i++) {
             node = navRoot.childNodes[i];
             if (node.nodeName=="A") {
                node.style.zIndex = zCount;
                zCount--;
                node.onmouseover=function() {
                    this.className+=" over";
                }
                node.onmouseout=function() {
                    this.className=this.className.replace(" over", "");
                }
             }
           }
       }
       if (document.getElementById("btn-permalink") != null) {
           navRoot = document.getElementById("btn-permalink");
           for (i=0; i<navRoot.childNodes.length; i++) {
             node = navRoot.childNodes[i];
             if (node.nodeName=="A") {
                node.style.zIndex = zCount;
                zCount--;
                node.onmouseover=function() {
                    this.className+=" over";
                }
                node.onmouseout=function() {
                    this.className=this.className.replace(" over", "");
                }
             }
           }
       }
       if (document.getElementById("btn-print") != null) {
           navRoot = document.getElementById("btn-print");
           for (i=0; i<navRoot.childNodes.length; i++) {
             node = navRoot.childNodes[i];
             if (node.nodeName=="A") {
                node.style.zIndex = zCount;
                zCount--;
                node.onmouseover=function() {
                    this.className+=" over";
                }
                node.onmouseout=function() {
                    this.className=this.className.replace(" over", "");
                }
             }
           }
       }
    }
}

addLoadEvent(startList);

// functions for navbar search filtering tabs
var srchTxtBox;
var srchTabs;
var srchInput;

function readySrchFilter() {
    srchTxtBox = document.getElementById("wm_srch_tabs");
	srchTabs   = srchTxtBox.getElementsByTagName("LI");
	srchInput = document.getElementById("wm_srch_query");
	/*srchInput.focus = showTabs;
	srchInput.onblur = hideTabs;*/
	
	for(var i = 0;i<srchTabs.length;i++) {
		// function to change the style of the selected filter */
		/* todo: make cookie to remember which filter was last selected (setFilterCookie)*/
		srchTabs[i].onclick = function() {
			for(var i = 0;i<srchTabs.length;i++) {
				srchTabs[i].className = "";	
			}
			this.className = "selected";
			//setHiddenField(this.title);
			setFormAction("nav_search", this.title);
			setFilterCookie(this.title);
		};	
	}
}
addLoadEvent(readySrchFilter);

function showTabs(){
	if(srchInput){
		srchTxtBox.display = "block";
	}
}

function hideTabs(){
	if(srchInput){
		srchTxtBox.display = "none";
	}
}

function setHiddenField(newVal){
	var hiddenField = document.getElementById("nav_srch_filter");
	if(hiddenField) {
		hiddenField.value = newVal;
	}
}

function setFormAction(formId, val){
    var form = document.getElementById(formId);
	if(form) {
		if(val != "all") {
			form.action = "/" + val + "/search/tag";
		}
		else if(val == "all") {
			form.action = "/search/tag";
		}
	}
}

function setFilterCookie(val){
    setCookie("lastSrchFilter", val, false, "", "/", "", false);
}

function getFilterCookie(){

}

/* function for making "Search" disappear on focus */
function readyTxtBoxes() {
    var inputEls = document.getElementsByTagName("INPUT");
    var clickCount = 0; // when page first loads, clickCount = 0
    
    for(var j=0;j < inputEls.length;j++) {
        if(inputEls[j].type=="text") {
            inputEls[j].onclick = function(){
                /* if this is the first time the user puts focus
                    on the text field or if the default text prompt 
                    is still in the field, erase it */
                if(clickCount == 0 ||this.value == "Search") {
                    this.value = "";
                    clickCount++;
                } 
            }
        }
    }
}
addLoadEvent(readyTxtBoxes);  


/********** functions for making sure search text boxes aren't blank ***********/
/* todo: combine into one func */

var cont_search;
var cont_srch_query;
var nav_search;
var nav_srch_query;
var create_page_query;

function checkSearchValExists(){
    cont_search = $("cont_search");
    cont_srch_query = $("cont_srch_query");
    nav_search = $("nav_search");
    nav_srch_query = $("keywords");
    create_page_query = $("mywikititle");
    
    if(cont_search) {cont_search.onsubmit = checkContSrchTxt;}
    if(nav_search)  {nav_search.onsubmit = checkNavSrchTxt;}
}
addLoadEvent(checkSearchValExists);

// check main content search component text area  value
function checkContSrchTxt(){
    if(cont_srch_query.value == "" || cont_srch_query.value == "Search") {
        returnError();
        return false;
    }
}

// check main nav search text area value
function checkNavSrchTxt(){
    if(nav_srch_query.value == "" || nav_srch_query.value == "Search" || create_page_query == "" || create_page_query == "Search") {
        returnError();
        return false;
    }
}      

function returnError(el){
    alert("please enter a search term");
}

/********* END quick and dirty text area checker *********/


/*function for preloading navbar images */
function preload_images(){
	if (document.images)
	{
  		pic1= new Image(); 
  		pic1.src="/images/nav-tut-hov-menutop_whole.png"; 
		
		pic2= new Image(); 
  		pic2.src="/images/nav-ref-hov-menutop_whole.png"; 
		
		pic3= new Image(); 
  		pic3.src="/images/nav-lib-hov-menutop_whole.png"; 
	}
}
addLoadEvent(preload_images);


/* quick, cursory js validation func for better user experience on contact us page */

var contactus_form;
var submit_button;
var fname_el;
var lname_el;
var email_el;
var subject_el;
var message_el;
var fname_error;
var lname_error;
var email_error;
var subject_error;
var message_error;

function readyForm(){
    contactus_form = $("contactus_form");
    submit_button = $("submit");
    fname_el = $("fname_el");
    lname_el = $("lname_el");
    email_el = $("email_el");
    subject_el = $("subject_el");
    message_el = $("message_el");
    fname_error = $("fname_error");
    lname_error = $("lname_error");
    email_error = $("email_error");
    subject_error = $("subject_error");
    message_error = $("message_error");
    
    if(submit_button) {
        contactus_form.onsubmit = verifyFormEntries;
        //contactus_form.onsubmit = killNow;
    }
}
// addLoadEvent(readyForm);

function killNow(){
    return false;
}

function verifyFormEntries(){
    if(fname_el.value == ""){
        fname_error.innerHTML = "Please enter your first name.";
        killNow();
    }
    if(lname_el.value == ""){
        lname_error.innerHTML = "Please enter your last name.";
        killNow();
    }
    if(email_el.value == ""){
        email_error.innerHTML = "Please enter your email address.";
        killNow();
    }
    if(subject_el.value == ""){
        subject_error.innerHTML = "Please enter the subject of this message.";
    }
    if(message_el.value == ""){
        message_error.innerHTML = "Please enter your message.";
    }
    else { contactus_form.submit };
    
}

/* for wiki index pages (requested article links) */
/* wiki index check for registration on requested article link click */
// not used right now
/*var reqArticleLinks;

function reqArtClickRegCheck(){
    reqArticleLinks = document.getElementsByClassName("reqart_link");
    
    for(var i=0;i<reqArticleLinks.length;i++) {
        alert("requested article link "+i);
        reqArticleLinks[i].onclick = runCheck;
    }
}
addLoadEvent(reqArtClickRegCheck);

function runCheck(){
    checkLogin(this.id);
}*/

/* social links */
document.write('<scr' + 'ipt type="text/javascript" src="http://w.sharethis.com/widget/?tabs=web%2Cemail&amp;charset=utf-8&amp;services=facebook%2Cmyspace%2Cdelicious%2Ctechnorati%2Cpropeller%2Cmixx%2Cnewsvine%2Cgoogle_bmarks%2Cyahoo_myweb%2Cwindows_live%2Ctailrank%2Cmagnolia%2Cfurl%2Cblinklist%2Cblogmarks&amp style=default&amp;publisher=0ec71848-688b-4d92-957d-d8ba67ad2647&amp;headerbg=%23e7e7e7&amp;inactivebg=%23f1f1f1&amp;inactivefg=%237e7e7e&amp;linkfg=%23007ca5"><\/script>');

function init_permalinkpage(){
    var sbm_title = document.title;
    var sbm_url = window.location;
    var redditLink = document.getElementById('redditLink');
    var diggLink = document.getElementById('diggLink');

    if(redditLink && diggLink) {
		redditLink.href = "http://reddit.com/submit?url=" + sbm_url + "&title=" + sbm_title;
		diggLink.href = "http://digg.com/submit?url=" + sbm_url + "&title=" + sbm_title;
	}
}

addLoadEvent(init_permalinkpage);

/*Footer Selects/Site Dropdowns*/
var cnp = window.cnp || {};
cnp.SelectNavigator = function(element){
    this.element = element;
    this.element.onchange = function(){
        var destination = this.options[this.selectedIndex].value;
        if(destination.match(/http.*/)){ 
            window.open(destination);
        }
    }
};
addLoadEvent(
function(){
    var footerSelects = document.getElementById('drop_downs').getElementsByTagName('SELECT');
    for(var i=0; i<footerSelects.length; i++){
        var select = new cnp.SelectNavigator(footerSelects[i]);
    }
});

