var baseHREF = $("base").attr("href");
$(function() {
	$('.attachTooltip').tipsy({gravity: 's'});
});

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;
        }
    });
};

function formatHtmlOutput(input){

	return html_entity_decode(stripslashes(input));
}

/*
	onclick="prepareFormFieldClear('cStatusUpdate','What have you done with this prospect today?',0);"
	onblur="prepareFormFieldClear('cStatusUpdate','What have you done with this prospect today?',1);"
*/
function prepareFormFieldClear(_cObjId, _cStrTxt, _iIsOnExit) {
	if (document.getElementById(_cObjId)) {
		var obj = document.getElementById(_cObjId);
		if (!_iIsOnExit && obj.value == _cStrTxt) {
			obj.value = '';
			obj.style.color = "#333333";
		} else if (_iIsOnExit && obj.value == '') {
			obj.style.color = "#cccccc";
			obj.value = _cStrTxt;
		}
	}
};

//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 to get Max z-index;
$.maxZIndex = $.fn.maxZIndex = function(opt) {
    /// <summary>
    /// Returns the max zOrder in the document (no parameter)
    /// Sets max zOrder by passing a non-zero number
    /// which gets added to the highest zOrder.
    /// </summary>
    /// <param name="opt" type="object">
    /// inc: increment value,
    /// group: selector for zIndex elements to find max for
    /// </param>
    /// <returns type="jQuery" />
    var def = { inc: 10, group: "*" };
    $.extend(def, opt);
    var zmax = 0;
    $(def.group).each(function() {
        var cur = parseInt($(this).css('z-index'));
        zmax = cur > zmax ? cur : zmax;
    });
    if (!this.jquery)
        return zmax;

    return this.each(function() {
        zmax += def.inc;
        $(this).css("z-index", zmax);
    });
}

function closeModal(id){
	$('#'+id).dialog('close');
};

//called once the event modal is loaded for calendar
function setActive(){
	//ajaxify the form
	if($('#form-eventAdd').length > 0){
		$('#form-eventAdd').submit(function(event){
			event.preventDefault();
			if($('#eventAdd-what').val() == ''){
				alert('Please enter a subject for the event');
			}else{
				$('#calendarProcesstype').val('ajax');
				$('#eventForm').addClass('loader');
				
				var oF = new rdAjaxPost({
					'cAction': $('#form-eventAdd').attr('action'),
					'oData': $('#form-eventAdd').serialize(),
					'receive_custom' : function(){
							sentCalEvent(result);
						    	},
					'cLogID' : 'nolog'
				}).send()
			}
		});
		
		$('input.DatePicker').datepicker({
			dateFormat: 'mm-dd-yy',
			beforeShow: function() {$('#ui-datepicker-div').maxZIndex();},
			onSelect: function() { $(".ui-datepicker a").removeAttr("href");}
		});

		//what page are we looking at?
		if(typeof( i ) != "undefined" ){
			for(i in curView){
				$('#form'+i).val(curView[i]);
			}
		}

		//add listeners to end date/ time etc
		$('#dStart').change(function(){
			updateCals(this);
		});

		$('#dEnd').change(function(){
			updateCals($(this));
		});

		$('#tStartHour, #tStartMinute, #tStartAmPm').change(function(){
		    updateTime($(this));
		});

		$('#tEndHour, #tEndMinute, #tEndAmPm').change(function(){
		    updateTime($(this));
		});

		//if delete event exists, add disable to that
		if($('#delEventCb').length > 0){
			$('#delEventCb').change(function(){

				if($(this).attr('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;
					});
				}
			});
		};

		$('#allDayCb').click(function(){
			
			if($(this).attr('checked') == false){
				$('.tCalTimeSelect').each(function(){
					$(this).css('display','inline');
				});
			} else {
				$('.tCalTimeSelect').each(function(){
					$(this).css('display','none');
				});
			}
		});
	};
	
	if( $('#form-eventAdd').length > 0 ){
		$('#form-eventAdd').submit(function(event){
			event.preventDefault();
			doSubmitEvent();
		});
	};
};

function updateTime(obj){

	tStartHour = parseInt($('#tStartHour').val());
	tEndHour =  parseInt($('#tEndHour').val());

//end time
if($('#tStartAmPm').val() == 'am' && tStartHour == 12  ){
		tStartHour = 0; 
}else if($('#tStartAmPm').val() == 'pm' && tStartHour != 12  ){
	tStartHour = tStartHour + 12; 
}
tStartHour = parseFloat(tStartHour + '.'+parseInt($('#tStartMinute').val()));

if($('#tEndAmPm').val() == 'am' && tEndHour == 12  ){
	tEndHour = 0; 
}else if($('#tEndAmPm').val() == 'pm' && tEndHour != 12  ){
	tEndHour = tEndHour + 12; 
}
//add the minutes
tEndHour = parseFloat(tEndHour + '.'+ parseInt($('#tEndMinute').val()));

	if (tEndHour < tStartHour){
		if($(obj).attr('id').indexOf("tStart") >= 0){
			var startHour = parseInt($('#tStartHour').val());
			if($('#tStartHour').val() == 12){
				if($('#tStartAmPm').val() == 'pm'){
					$('#tEndHour').val(12);
				}else{
					$('#tEndHour').val(1);
				}
			}else{
				$('#tEndHour').val(startHour + 1);
			}
			$('#tEndMinute').val($('#tStartMinute').val());
			
			if($('#tStartHour').val() == 11){
				if($('#tStartAmPm').val() == 'pm'){
					$('#tEndAmPm').val('am');
				}else{
					$('#tEndAmPm').val('pm');
				}
			}else{
				$('#tEndAmPm').val($('#tStartAmPm').val());
			}
		} else {
			var endHour = parseInt($('#tEndHour').val());
			
			//if 12 am, can't go before that
			if($('#tEndHour').val() == 12 && $('#tEndAmPm').val() == 'am'){
				$('#tStartHour').val(12)
			}else if($('#tEndHour').val() == 1){
				$('#tStartHour').val(12);
			}else{
				$('#tStartHour').val(endHour - 1);
			}
			$('#tStartMinute').val($('#tEndMinute').val());
			
			if($('#tEndHour').val() == 12){
				if($('#tEndAmPm').val() == 'pm'){
					$('#tStartAmPm').val('am');
				}
			}else{
				$('#tStartAmPm').val($('#tEndAmPm').val());
			}
		};
	};

};


function calUpdateTime(obj){
	
	var startDate = $("#actionCaldStart").val();
	var endDate = $("#actionCaldEnd").val();
	var aStartDateParts = startDate.split('-',3);
	var aEndDateParts   = endDate.split('-',3);
	var startMonth = aStartDateParts[0];
	var startDay   = aStartDateParts[1];
	var endMonth = aEndDateParts[0];
	var endDay   = aEndDateParts[1];
	
	if(startDay == endDay && startMonth == endMonth){
		tStartHour = parseInt($('#actionCaltStartHour').val());
		tEndHour =  parseInt($('#actionCaltEndHour').val());
	
		//end time
		if($('#actionCaltStartAmPm').val() == 'am' && tStartHour == 12  ){
				tStartHour = 0; 
		}else if($('#actionCaltStartAmPm').val() == 'pm' && tStartHour != 12  ){
			tStartHour = tStartHour + 12; 
		}
		tStartHour = parseFloat(tStartHour + '.'+parseInt($('#actionCaltStartMinute').val()));
		
		if($('#actionCaltEndAmPm').val() == 'am' && tEndHour == 12  ){
			tEndHour = 0; 
		}else if($('#actionCaltEndAmPm').val() == 'pm' && tEndHour != 12  ){
			tEndHour = tEndHour + 12; 
		}
		//add the minutes
		tEndHour = parseFloat(tEndHour + '.'+ parseInt($('#actionCaltEndMinute').val()));
	
		if (tEndHour < tStartHour){
			if($(obj).attr('id').indexOf("actionCaltStart") >= 0){
				var startHour = parseInt($('#actionCaltStartHour').val());
				if($('#actionCaltStartHour').val() == 12){
					if($('#actionCaltStartAmPm').val() == 'pm'){
						$('#actionCaltEndHour').val(12);
					}else{
						$('#actionCaltEndHour').val(1);
					}
				}else{
					$('#actionCaltEndHour').val(startHour + 1);
				}
				$('#actionCaltEndMinute').val($('#actionCaltStartMinute').val());
				
				if($('#actionCaltStartHour').val() == 11){
					if($('#actionCaltStartAmPm').val() == 'pm'){
						$('#actionCaltEndAmPm').val('am');
					}else{
						$('#actionCaltEndAmPm').val('pm');
					}
				}else{
					$('#actionCaltEndAmPm').val($('#actionCaltStartAmPm').val());
				}
			} else {
				var endHour = parseInt($('#actionCaltEndHour').val());
				
				//if 12 am, can't go before that
				if($('#actionCaltEndHour').val() == 12 && $('#actionCaltEndAmPm').val() == 'am'){
					$('#actionCaltStartHour').val(12)
				}else if($('#actionCaltEndHour').val() == 1){
					$('#actionCaltStartHour').val(12);
				}else{
					$('#actionCaltStartHour').val(endHour - 1);
				}
				$('#actionCaltStartMinute').val($('#actionCaltEndMinute').val());
				
				if($('#actionCaltEndHour').val() == 12){
					if($('#actionCaltEndAmPm').val() == 'pm'){
						$('#actionCaltStartAmPm').val('am');
					}
				}else{
					$('#actionCaltStartAmPm').val($('#actionCaltEndAmPm').val());
				}
			};
		};
	}

};
