//baseuri for IE
var baseHREF = document.getElementsByTagName('base')[0].href;

function templateLoadHREF(loc) {
	if (loc) {
		document.location = loc;
	};
};

window.addEvent('domready', function(){

	if(window.ie6){

	};

/*    if ($('subNavHelpDesk')){
		$('subNavHelpDesk').addEvent('click', function(e){
			new Event(e).stop();
			document.mochaDesktop.newWindow({
				id: 'modalHelpDesk',
				title: 'Help Desk',
				loadMethod: 'xhr',
				contentURL: 'help-desk/index/ajax',
				modal: true,
				width: 850,
				height: 500,
				x:0,
				y:100,
				closable: true,
				onContentLoaded: initHelpTab,
				headerStartColor:  [250, 250, 250],
	            headerStopColor:   [200, 220, 240],
	            closeColor: [180, 200, 220]
			});
		});
	};*/

	sfEls = $$('ul#mainNav li.mainTab');

	sfEls.each(function(el){
		el.addEvent ('mouseover', function(){
			this.addClass('sfhover');
		});
		el.addEvent ('mouseout', function(){
			this.removeClass('sfhover');
		});

	});
	
	
});

function viewHelpDesk(){
	
	document.mochaDesktop.newWindow({
		id: 'modalHelpDesk',
		title: 'Help Desk',
		loadMethod: 'xhr',
		contentURL: 'help-desk/index/ajax',
		modal: true,
		width: 450,
		height: 250,
		x:0,
		y:100,
		closable: true,
		headerStartColor:  [250, 250, 250],
        headerStopColor:   [200, 220, 240],
        closeColor: [180, 200, 220]
	});
	
}

function closeModal(id){
	document.mochaDesktop.closeWindow($(id));
};

function updateProspectLink(CID){
	if(CID!=''){
		$('prospectLink').style.display='inline';
		$('prospectLink').href='prospect-manager/prospect/view/iCID/'+ CID;
	}else{
		$('prospectLink').style.display='none';
	}
}


//called once the event modal is loaded for calendar
function setActive(){
	//ajaxify the form
	if($('form-eventAdd')){
		$('form-eventAdd').addEvent('submit', function(e){
			new Event(e).stop();
			if($('eventAdd-what').value==''){
				alert('Please enter a subject for the event');
			}else{
				$('calendarProcesstype').value = 'ajax';
				$('eventForm').addClass('loader');
				this.send({
					onComplete: sentCalEvent
				});
			}
		});

		dateStart = new DatePicker($('dStart'));
		dateEnd = new DatePicker($('dEnd'));

		//what page are we looking at?
		if(typeof( i ) != "undefined" ){
			for(i in curView){
				$('form'+i).value = curView[i];
			}
		}

		//add listeners to end date/ time etc
		$('dStart').addEvent('change', function(){
			updateCals(this);
		});

		$('dEnd').addEvent('change', function(){
			updateCals(this);
		});

		$('tStart').addEvent('change', function(){
		    updateTime(this);
		});

		$('tEnd').addEvent('change', function(){
		    updateTime(this);
		});

		//if delete event exists, add disable to that
		if($('delEventCb')){
			$('delEventCb').addEvent('change', function(){

				if(this.checked == false){
					$$('#eventForm input[type!=hidden]', '#eventForm select', '#eventForm textarea').each(function(i){
					    i.disabled = false;
					});
				} else {
					$$('#eventForm input[type!=hidden]', '#eventForm select', '#eventForm textarea').each(function(i){
						if(i.type != 'submit' && i.name !='iDelete')
		        				i.disabled = true;
					});
				}
			});
		};

		if($('allDayCb').checked === true) {
			$('tStart').style.visibility = 'hidden';
			$('tEnd').style.visibility = 'hidden';
		};

		$('allDayCb').addEvent('click', function(){
			
			if(this.checked == false){
				//$('tStart').disabled=false;
				//$('tEnd').disabled=false;
				$('tStart').style.visibility = 'visible';
				$('tEnd').style.visibility = 'visible';
			} else {
				//$('tStart').value='0';
				//$('tEnd').value='23';
				//$('tStart').disabled=true;
				//$('tEnd').disabled=true;
				$('tStart').style.visibility = 'hidden';
				$('tEnd').style.visibility = 'hidden';
			}
		});
	};
	
	if( f = $('form-eventAdd') ){
		f.addEvent('submit', function(e){
			new Event(e).stop();
			doSubmitEvent();
		});
	};
};

//date check
function updateCals(obj){
	
	d = new Date();
	var now = d.getTime();

	if ($('dStart') && $('dEnd')){
		//there is an event modal with day start and day end.  make sure the day end is not before day start
		dStart = $('dStart');
		dEnd = $('dEnd');

		iStart = Date.parse(dStart.value.replace(/-/g,"/"));
		iEnd = Date.parse(dEnd.value.replace(/-/g,"/"));

		//start date is less than end date
		if(iEnd<iStart){
			if(obj == dStart){
				//start date was changed. update the end date select
				dEnd.value = dStart.value;
				endDate = new Date(iStart);
				dateEnd.formatValue($('dEnd'), endDate.getFullYear(), endDate.getMonth()+1, endDate.getDate());
			} else {
				//end date was changed. update the start date select
				dStart.value = dEnd.value;
				startDate = new Date(iEnd);
				dateStart.formatValue($('dStart'), startDate.getFullYear(), startDate.getMonth()+1, startDate.getDate());
			}
		}

		if(iStart != iEnd){
			/*
			if($('allDayCb').checked == true){
				$('allDayCb').checked = false;
				$('tStart').style.visibility = 'visible';
				$('tEnd').style.visibility = 'visible';
			}
			
			//$('allDayCb').disabled = true;
			*/
		}else{
			//$('allDayCb').disabled = false;
		};
	};
};

//time check
function updateTime(obj){

	tStart = $('tStart');
	tEnd = $('tEnd');

	iStart = parseFloat(tStart.value);
	iEnd = parseFloat(tEnd.value);

	if (iEnd < iStart){
		if(obj == tStart){
			tEnd.value= iStart + .5;
		} else {
			tStart.value= iEnd - .5 ;
		};
	};

};

function editEventModal(iEventID,currentView,year,month,day){
	document.mochaDesktop.newWindow({
		id: 'viewEvent',
		title: 'Edit Event',
		loadMethod: 'xhr',
		contentURL: 'calendar/event/create/processType/ajax/iEventID/'+iEventID+'/currentView/'+currentView+'/year/'+year+'/month/'+month+'/day/'+day,
		modal: true,
		width: 650,
		height: 500,
		x: 0,
		y: window.getScrollTop() + 100,
		closable: true,
		onContentLoaded: setActive,
		headerStartColor:  [250, 250, 250],
	          headerStopColor:   [200, 220, 240],
	          closeColor: [180, 200, 220]
	});
};

function viewTrainingMedia(cMedia){	
	document.mochaDesktop.newWindow({
		id: 'trainingMedia',
		title: 'Training Media',
		loadMethod: 'iframe',
		contentURL: 'media/index/cMedia/'+cMedia,
		modal: true,
		width: 460,
		height: 360,
		x: 0,
		y: window.getScrollTop() + 100,
		closable: true,
		scrollbars: false,
		onContentLoaded: setActive,
		headerStartColor:  [250, 250, 250],
	          headerStopColor:   [200, 220, 240],
	          closeColor: [180, 200, 220]
	});
};


//similar to php trim
function trim( str, charlist ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: mdsjack (http://www.mdsjack.bo.it)
    // +   improved by: Alexander Ermolaev (http://snippets.dzone.com/user/AlexanderErmolaev)
    // +      input by: Erkekjetter
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: DxGx
    // +   improved by: Steven Levithan (http://blog.stevenlevithan.com)
    // *     example 1: trim('    Kevin van Zonneveld    ');
    // *     returns 1: 'Kevin van Zonneveld'
    // *     example 2: trim('Hello World', 'Hdle');
    // *     returns 2: 'o Wor'

    var whitespace;

    if (!charlist) {
        whitespace = ' \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000';
    } else {
        whitespace = charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '\$1');
    };

    for (var i = 0; i < str.length; i++) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(i);
            break;
        };
    };
    for (i = str.length - 1; i >= 0; i--) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(0, i + 1);
            break;
        };
    };
    return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
};

//formats the phone field to ##########
function unformatPhone(num){
    var re= /\D/;
    
    while (re.test(num)){
        num = num.replace(re,"");
    };
    
    return num;
};

//formats the phone field to (###) ###-####?
function formatPhone(num){

    var re= /\D/;
    // test for this format: (xxx)xxx-xxxx
    var re2 = /^\({1}\d{3}\)\d{3}-\d{4}/;
    // test for this format: xxx-xxx-xxxx

	var newNum;

	if (num != "" && re2.test(num)!=true){
        if (num != ""){
            while (re.test(num)){
                num = num.replace(re,"");
            };
        };

        if (num.toString().length != 10){
            //no good! alert something?
        }  else {
            // for format (xxx)xxx-xxxx
            area_code = num.substring(0,3);
            homephone1 = num.substring(3,6);
            homephone2 = num.substring(6,10);

            newNum = '(' + area_code + ')' + homephone1 + '-' + homephone2;

        };
    };
    
    return newNum;
};

// Open New Window
function initPopUp(cURL) {
	window.open(cURL);
}

function strip_tags(str, allowed_tags) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Luke Godfrey
    // +      input by: Pul
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: strip_tags('<p>Kevin</p> <br /><b>van</b> <i>Zonneveld</i>', '<i>,<b>');
    // *     returns 1: 'Kevin <b>van</b> <i>Zonneveld</i>'
    // *     example 2: strip_tags('<p>Kevin <img src="someimage.png" onmouseover="someFunction()">van <i>Zonneveld</i></p>', '<p>');
    // *     returns 2: '<p>Kevin van Zonneveld</p>'
    // *     example 3: strip_tags("<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>", "<a>");
    // *     returns 3: '<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>'

    var key = '', tag = '', allowed = false;
    var matches = allowed_array = [];
    var allowed_keys = {};

    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };

    // Build allowes tags associative array
    if (allowed_tags) {
        allowed_tags  = allowed_tags.replace(/[^a-zA-Z,]+/g, '');;
        allowed_array = allowed_tags.split(',');
    };

    // Match tags
    matches = str.match(/(<\/?[^>]+>)/gi);

    // Go through all HTML tags
    for (key in matches) {
        if (isNaN(key)) {
            // IE7 Hack
            continue;
        };

        // Save HTML tag
        html = matches[key].toString();

        // Is tag not in allowed list? Remove from str!
        allowed = false;

        // Go through all allowed tags
        for (k in allowed_array) {
            // Init
            allowed_tag = allowed_array[k];
            i = -1;

            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+'>');}
            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+' ');}
            if (i != 0) { i = html.toLowerCase().indexOf('</'+allowed_tag)   ;}

            // Determine
            if (i == 0) {
                allowed = true;
                break;
            };
        };

        if (!allowed) {
            str = replacer(html, "", str); // Custom replace. No regexing
        };
    }

    return str;
};

function stripslashes( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +      fixed by: Mick@el
    // +   improved by: marrtins
    // +   bugfixed by: Onno Marsman
    // *     example 1: stripslashes('Kevin\'s code');
    // *     returns 1: "Kevin's code"

    return (str+'').replace('/\0/g', '0').replace('/\(.)/g', '$1');
};

function html_entity_decode( string ) {
    // http://kevin.vanzonneveld.net
    // +   original by: john (http://www.jd-tech.net)
    // +      input by: ger
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // %          note: table from http://www.the-art-of-web.com/html/character-codes/
    // *     example 1: html_entity_decode('Kevin &amp; van Zonneveld');
    // *     returns 1: 'Kevin & van Zonneveld'

    var histogram = {}, histogram_r = {}, code = 0;
    var entity = chr = '';

    histogram['34'] = 'quot';
    histogram['38'] = 'amp';
    histogram['60'] = 'lt';
    histogram['62'] = 'gt';
    histogram['160'] = 'nbsp';
    histogram['161'] = 'iexcl';
    histogram['162'] = 'cent';
    histogram['163'] = 'pound';
    histogram['164'] = 'curren';
    histogram['165'] = 'yen';
    histogram['166'] = 'brvbar';
    histogram['167'] = 'sect';
    histogram['168'] = 'uml';
    histogram['169'] = 'copy';
    histogram['170'] = 'ordf';
    histogram['171'] = 'laquo';
    histogram['172'] = 'not';
    histogram['173'] = 'shy';
    histogram['174'] = 'reg';
    histogram['175'] = 'macr';
    histogram['176'] = 'deg';
    histogram['177'] = 'plusmn';
    histogram['178'] = 'sup2';
    histogram['179'] = 'sup3';
    histogram['180'] = 'acute';
    histogram['181'] = 'micro';
    histogram['182'] = 'para';
    histogram['183'] = 'middot';
    histogram['184'] = 'cedil';
    histogram['185'] = 'sup1';
    histogram['186'] = 'ordm';
    histogram['187'] = 'raquo';
    histogram['188'] = 'frac14';
    histogram['189'] = 'frac12';
    histogram['190'] = 'frac34';
    histogram['191'] = 'iquest';
    histogram['192'] = 'Agrave';
    histogram['193'] = 'Aacute';
    histogram['194'] = 'Acirc';
    histogram['195'] = 'Atilde';
    histogram['196'] = 'Auml';
    histogram['197'] = 'Aring';
    histogram['198'] = 'AElig';
    histogram['199'] = 'Ccedil';
    histogram['200'] = 'Egrave';
    histogram['201'] = 'Eacute';
    histogram['202'] = 'Ecirc';
    histogram['203'] = 'Euml';
    histogram['204'] = 'Igrave';
    histogram['205'] = 'Iacute';
    histogram['206'] = 'Icirc';
    histogram['207'] = 'Iuml';
    histogram['208'] = 'ETH';
    histogram['209'] = 'Ntilde';
    histogram['210'] = 'Ograve';
    histogram['211'] = 'Oacute';
    histogram['212'] = 'Ocirc';
    histogram['213'] = 'Otilde';
    histogram['214'] = 'Ouml';
    histogram['215'] = 'times';
    histogram['216'] = 'Oslash';
    histogram['217'] = 'Ugrave';
    histogram['218'] = 'Uacute';
    histogram['219'] = 'Ucirc';
    histogram['220'] = 'Uuml';
    histogram['221'] = 'Yacute';
    histogram['222'] = 'THORN';
    histogram['223'] = 'szlig';
    histogram['224'] = 'agrave';
    histogram['225'] = 'aacute';
    histogram['226'] = 'acirc';
    histogram['227'] = 'atilde';
    histogram['228'] = 'auml';
    histogram['229'] = 'aring';
    histogram['230'] = 'aelig';
    histogram['231'] = 'ccedil';
    histogram['232'] = 'egrave';
    histogram['233'] = 'eacute';
    histogram['234'] = 'ecirc';
    histogram['235'] = 'euml';
    histogram['236'] = 'igrave';
    histogram['237'] = 'iacute';
    histogram['238'] = 'icirc';
    histogram['239'] = 'iuml';
    histogram['240'] = 'eth';
    histogram['241'] = 'ntilde';
    histogram['242'] = 'ograve';
    histogram['243'] = 'oacute';
    histogram['244'] = 'ocirc';
    histogram['245'] = 'otilde';
    histogram['246'] = 'ouml';
    histogram['247'] = 'divide';
    histogram['248'] = 'oslash';
    histogram['249'] = 'ugrave';
    histogram['250'] = 'uacute';
    histogram['251'] = 'ucirc';
    histogram['252'] = 'uuml';
    histogram['253'] = 'yacute';
    histogram['254'] = 'thorn';
    histogram['255'] = 'yuml';

    // Reverse table. Cause for maintainability purposes, the histogram is
    // identical to the one in htmlentities.
    for (code in histogram) {
        entity = histogram[code];
        histogram_r[entity] = code;
    }

    return (string+'').replace(/(\&([a-zA-Z]+)\;)/g, function(full, m1, m2){
        if (m2 in histogram_r) {
            return String.fromCharCode(histogram_r[m2]);
        } else {
            return m2;
        }
    });
};
/**
 * Properly redirect using the bas href.  This is needed since IE doesn't take the base href into
 * account when doing an document.location redirect
 * @param loc
 * @return
 */
function redirect(loc){
	 var b = document.getElementsByTagName('base');
	 if (b && b[0] && b[0].href) {
	   if (b[0].href.substr(b[0].href.length-1) == '/' && loc.charAt(0) == '/')
	     loc = loc.substr(1);
	   loc = b[0].href + loc;
	 }
	 document.location = loc;
}

function toggleActiveElement(cID) {
	if (cID && document.getElementById(cID)) {
		var cObj = document.getElementById(cID);
		if (cObj.style.display != 'block') {
			cObj.style.display = 'block';
		} else {
			cObj.style.display = 'none';
		}
	}
};

