/*
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */

var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};

function categorySelector(el){
	if(el.value){
		location.href = el.value
	}
}

function faqShow(obj){
	objGet = document.getElementById(obj);
	if(objGet.className == "answer"){
		objGet.className = "answerShow";
	}else{
		objGet.className = "answer";
	}
}

//
function showDiv(obj){
	el = document.getElementById(obj);
	if(el.className == "hide"){
		el.className = "show";
	}else{
		el.className = "hide";
	}
	
}

var questionSubmitted=false;

function validateQuestionAndSubmit(){
	if(questionSubmitted){
		return false;
	}

	var f=document.forms['question_form'];
	
	if(!f){
		return false;
	}	
	
	var title=$("#question_title").val();
	var text=$("#question_text").val();
	
	var titleOK=title!='' && title!=$("#question_title").attr('rel');
	var textOK=text!='' && text!=$("#question_text").attr('rel');	
	
	if(!titleOK){
		alert('Please enter a question title!');
		return false;
	}
	
	var maxl=2000;
	
	if(text.length>maxl){
		alert('Question text exceeded the maximum length of '+maxl+' chars');
		return false;
	}
	
	questionSubmitted=true;
	
	if($("#media_url").val()==$("#media_url").attr('rel')){
		$("#media_url").val('');
	}
	
	if($("#media_description").val()==$("#media_description").attr('rel')){
		$("#media_description").val('');
	}
	
	f.submit();
}

var answerSubmitted=false;

function validateAnswerAndSubmit(){
	
	if(answerSubmitted){
		return false;
	}
	var f=document.forms['answer_form'];
	
	if(!f){
		return false;
	}
	
	if(f.the_answer.value==''){
		alert('Please enter an answer!');
		return false;
	}
	
	answerSubmitted=true;
	
	f.submit();	
}

function postAnswer(){
	document.getElementById('linkAnswer').className = "linkAnswerSelect whitetext";
	document.getElementById('questionInput').className = "questionInputShow";
	document.getElementById('changeLinkPost').className = "postananswerlink";

}
function sendForm(formID){

	myform	=	document.getElementById(formID);
	myform.submit();
}

var intervalId;
var messageDiv;

function fadeOutMessage(idDiv){
	messageDiv = idDiv;
	intervalId = setInterval("hideMessage()",15000);
}

function hideMessage(){

	clearInterval(intervalId);
	opacity(messageDiv, 100, 0, 500);
	if(document.all) document.getElementById(messageDiv).style.display = "none";

}

function opacity(id, opacStart, opacEnd, millisec) {
    //speed for each frame
    var speed = Math.round(millisec / 100);
    var timer = 0;

    //determine the direction for the blending, if start and end are the same nothing happens
    if(opacStart > opacEnd) {
        for(i = opacStart; i >= opacEnd; i--) {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    } else if(opacStart < opacEnd) {
        for(i = opacStart; i <= opacEnd; i++)
            {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    }
}

//change the opacity for different browsers
function changeOpac(opacity, id) {
    var object = document.getElementById(id).style;
    object.opacity = (opacity / 100);
    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
    object.filter = "alpha(opacity=" + opacity + ")";
}


var captchaLoaded=false;
function fCheckDefault(rInput, vDefaultValue)
{
    var lEmptyClassName = 'empty';
    
    if(rInput.value.toLowerCase() == vDefaultValue.toLowerCase()) {
    
        rInput.value = '';
    }
    rInput.className = rInput.className.replace(' ' + lEmptyClassName, '');
}
function fPutDefault(rInput, vDefaultValue)
{
	
    var lEmptyClassName = 'empty';
    
    if(rInput.value == '' || rInput.value.toLowerCase() == vDefaultValue.toLowerCase()) {
    
        rInput.className += ' ' + lEmptyClassName;
        rInput.value = vDefaultValue;
    }
}

function changeTab(val){
	
		switch(val){
			case 1:
				try {
					document.getElementById('question_results').className = "searchShow";
					document.getElementById('answer_results').className = "searchHide";
					document.getElementById('article_results').className = "searchHide";
				}
				catch(err)
				  {
				  //Handle errors here
				  }
				document.getElementById('answertab').className = "";
				document.getElementById('questiontab').className = "active";
				document.getElementById('articletab').className = "";
			break;
			case 2:
				try {
					document.getElementById('question_results').className = "searchHide";
					document.getElementById('answer_results').className = "searchShow";
					document.getElementById('article_results').className = "searchHide";
				}
				catch(err)
				  {
				  //Handle errors here
				  }
				document.getElementById('answertab').className = "active";
				document.getElementById('questiontab').className = "";
				document.getElementById('articletab').className = "";
					
			break;
			case 3:
				try {
					document.getElementById('question_results').className = "searchHide";
					document.getElementById('answer_results').className = "searchHide";
					document.getElementById('article_results').className = "searchShow";
				}
				catch(err)
				  {
				  //Handle errors here
				  }
					
				document.getElementById('answertab').className = "";
				document.getElementById('questiontab').className = "";
				document.getElementById('articletab').className = "active";
					
			break;			
			case 4:
				try {
					document.getElementById('question_results').className = "searchHide";
					document.getElementById('answer_results').className = "searchHide";
					document.getElementById('article_results').className = "searchHide";
				}
				catch(err)
				{
					//Handle errors here
				}
				
				document.getElementById('answertab').className = "";
				document.getElementById('questiontab').className = "";
				document.getElementById('articletab').className = "";
				
				break;			
		}
	
	
	query = document.getElementById('query')
	query.focus();
}


function changeTab2(val){
	
	switch(val){
	case 1:
		try {
			document.getElementById('question_results').className = "searchShow";
			document.getElementById('answer_results').className = "searchHide";
			document.getElementById('article_results').className = "searchHide";
			document.getElementById('web_results').className = "searchHide";
		}
		catch(err)
		{
			//Handle errors here
		}
		document.getElementById('answertab').className = "";
		document.getElementById('questiontab').className = "active";
		document.getElementById('articletab').className = "";
		document.getElementById('webtab').className = "";
		break;
	case 2:
		try {
			document.getElementById('question_results').className = "searchHide";
			document.getElementById('answer_results').className = "searchShow";
			document.getElementById('article_results').className = "searchHide";
			document.getElementById('web_results').className = "searchHide";
		}
		catch(err)
		{
			//Handle errors here
		}
		document.getElementById('answertab').className = "active";
		document.getElementById('questiontab').className = "";
		document.getElementById('articletab').className = "";
		document.getElementById('webtab').className = "";
		
		break;
	case 3:
		try {
			document.getElementById('question_results').className = "searchHide";
			document.getElementById('answer_results').className = "searchHide";
			document.getElementById('article_results').className = "searchShow";
			document.getElementById('web_results').className = "searchHide";
		}
		catch(err)
		{
			//Handle errors here
		}
		
		document.getElementById('answertab').className = "";
		document.getElementById('questiontab').className = "";
		document.getElementById('articletab').className = "active";
		document.getElementById('webtab').className = "";
		
		break;			
	case 4:
		try {
			document.getElementById('question_results').className = "searchHide";
			document.getElementById('answer_results').className = "searchHide";
			document.getElementById('article_results').className = "searchHide";
			document.getElementById('web_results').className = "searchShow";
		}
		catch(err)
		{
			//Handle errors here
		}
		
		document.getElementById('answertab').className = "";
		document.getElementById('questiontab').className = "";
		document.getElementById('articletab').className = "";
		document.getElementById('webtab').className = "active";
		
		break;			
	}
	
	
	query = document.getElementById('query')
	query.focus();
}

function showQuestionForm() {
	$("#question_title").click(function () {
		openQuestionForm();
	});
}

function openQuestionForm(){
	refreshSubmitButtonStatus();
	$("#posting-tool").css('display','block');
	$("#medialinks").css('display','block');	
}

function noenter() {
	return !(window.event && window.event.keyCode == 13);
}

function refreshSubmitButtonStatus(){
	
	var title=$("#question_title").val();
	var text=$("#question_text").val();
	
	var titleOK=title!='' && title!=$("#question_title").attr('rel');
	var textOK=text!='' && text!=$("#question_text").attr('rel');

	if(titleOK && textOK){
		$("#submit-question-button").removeAttr("disabled");
	}
	else{
		$("#submit-question-button").attr("disabled","disabled");
	}
}

$(document).ready(function() {
	
	$('.date.chooser').dynDateTime({
		showsTime: false,
		ifFormat: "%d-%m-%Y",
		daFormat: "%d-%m-%Y",
		align: "BR",
		weekNumbers:  false,
		electric: true,
		displayArea: ".siblings('.dtcDisplayArea')"
	});
	
	$('img.trigger').toggle(
		function (){
			//$($(this).attr('rel')).css("display", "block");
			$($(this).attr('rel')).slideDown();
		},
		function (){
			//$($(this).attr('rel')).css("display", "none");
			$($(this).attr('rel')).slideUp();
		}
	);
	
	$('.autoval').each(function() {
		$(this).attr('value',$(this).attr('rel'));
		//$(this).attr('rel',$(this).attr('value'));
	});

	$('.autoval').focus(function() {
		refreshSubmitButtonStatus();
		if ($(this).attr('value') == $(this).attr('rel')) {
			$(this).attr('value','');
		}
		if($(this).attr('id')=='question_title'){
			openQuestionForm();
		}
	});
	
	$('.autoval').blur(function() {
		refreshSubmitButtonStatus();
		if ($(this).attr('value') == '') {
			$(this).attr('value',$(this).attr('rel'));
		}
	});

	
	$("#topicButton a").toggle(
	  function () {
		$("#menu ul li ul").css("display", "block");
		$("#topicButton").attr('class', 'expanded');
		$("#topicButton a").attr('title', 'Click to Hide Subtopics');
	  },
	  function () {
		  $("#menu ul li ul").css("display", "none");
		$("#topicButton").attr('class', 'collapsed');
		$("#topicButton a").attr('title', 'Click to see All Topics');
	  }

	);
	
	$("a.trigger").toggle(
	  function () {
		//  $("a.trigger + form").fadeOut();
		  $("a.trigger + form").slideDown();
	  },
	  function () {
		  //$("a.trigger + form").fadeIn();
		  $("a.trigger + form").slideUp();
	  }

	);

	showQuestionForm();

});
