String.prototype.toProperCase = function()
{
  return this.toLowerCase().replace(/^(.)|\s(.)/g,
      function($1) { return $1.toUpperCase(); });
}
//returns Difference in years, works with 2 date obects
function DateDiffYears(datefrom,dateto)
{
    var years =  dateto.getFullYear() - datefrom.getFullYear();
    if (dateto.getMonth() < datefrom.getMonth())
	years = years -1; // if too early in the year by MONTHS, decrease one from the diff
    else if((dateto.getMonth() == datefrom.getMonth()) && (dateto.getDate() < datefrom.getDate()))
	years = years -1; //if the same month, and too early by DAYS, decrease by one year
    return years;
}
function DictLookup(dList,str,str2)
{
    var strlookup = str;
    if (str2) strlookup += '[' + str2 + ']';
    return dList[strlookup] ? dList[strlookup] : str;
}
function getFirstCapital(str)
{
	if(str != '')
	{
		var first = str.charAt(0);
		return first.toUpperCase()+str.substring(1, str.length);
	}
	return '';
}
function DoubleSlashSpecial(propertyName)
{
  function addSlash(match)
  {
    return '\\' + match;
  }
  return propertyName.replace(/[\@\#\;\&\,\.\+\*\~\'\:\"\!\^\$\[\]\(\)\=\>\|\/\\]/g, addSlash);
}
function validateLoginForm(checkpass)
{
    var email = $('#login_email').val();
	var isValid = true;
	$('.errors').remove();
	if(email == '')
	{
		$('#login_email').before('<p class="errors">Please enter your email address</p>');
		isValid = false;
	}
	else
	{
		if (!email_validation(email))
		    {
			$('#login_email').before('<p class="errors">Please enter a valid email address</p>');
			isValid = false;
		    }
		   else {
			   
			if((jQuery("#login_options > li div:visible").length)==0)
			{
			     showErrorDlg('Email Provider Not Supported','Sorry, at this point we only support Yahoo and Gmail accounts, we will notify you when we add support to other accounts.');
			    isValid = false;
			} else {
				new $.ajax({
					async: 		true,
					url: 		connectUrl+'checkAcctInvited?email='+email,
					success: 	function(response)
					{
						if (response!='')
						showErrorDlg('Not Invited',response);
					},
					type:   	'GET'
				});
			}
		}
	}
	var pass = $('#login_pass').val();
	if(pass == '' && checkpass)
	{
		isValid = false;
		$('#login_pass').before('<p class="errors">Please enter your password</p>');
	}
	return isValid;
}
function showDownloadWait(form,checkpass)
{
	var email = $('#login_email').val();
	var isValid = validateLoginForm(checkpass);
	
	if(isValid)
	{
		new $.ajax({
			async: 		true,
			url: 		connectUrl+'checkAcctNotified?email='+email,
			error: 		function(XMLHttpRequest)
			{				
				showWaitDlg('We are loading your contacts, this might take a while.');
				form.submit();
			},
			success: 	function(response)
			{
				showWaitDlg('Please Wait while we log you into the account');
				form.submit();
				$(form).submit(function() {return false;});
			},
			type:   	'GET'
		});
	}
	
	return false;
}

function email_validation(email)
{
	var regExpNonStrictEmail = /^([0-9A-Za-z_\!\.\-]+)\@(([0-9A-Za-z\-]+\.)+[0-9A-Za-z]{2,4})$/;
	if (!regExpNonStrictEmail.test(email))
	{
	  return false;
	}
	else return true;
}

function showWaitDlg(msg)
{
	new $('<div></div>')
	.html(msg)
	.dialog({
		autoOpen: true,
		title: '<img src="/images/ajax_loader_s.gif" />&nbsp;&nbsp;&nbsp;Please wait',
		height: 50,
		buttons: {},
		closeOnEscape: false,
		draggable: false,
		resizable: false,
		modal: true,
		open: function(event, ui) {jQuery('.ui-dialog-titlebar-close').hide();}
	});
}
function showErrorDlg(title,msg)
{
	ErrorDialog = new CMDialog();
	ErrorDialog.SetTitle(title);
	ErrorDialog.SetMsg(msg);
	ErrorDialog.SetCloseButton(true);
	ErrorDialog.SetHeight(200);
	ErrorDialog.Show(true);
}
function FilterDSN(dsn)
{
	var filteredDsn = dsn.replace(/(\W)+/, '');
	if(filteredDsn.length > 20) filteredDsn = filteredDsn.substr(0,20);
	return filteredDsn;
}

function showPassTerms()
{
	var $passDialog = $('<div></div>')
		.html('We only use your password once to verify your identity and to import your address-book information, once this is done - your password is deleted.')
		.dialog({
			autoOpen: false,
			title: 'How do we use password',
			draggable: false,
			resizable: false,
			modal: true,
			buttons: {"Close": function() {$(this).dialog("close");}}
		});
	
	$('#learn_more').click(function() {
		$passDialog.dialog('open');
	});
}

function showWelcome()
{
	CMDialog = new CMDialog();
	if(contList.length==0)
	{
		CMDialog.SetTitle('Welcome to your enriched contact book!');
		CMDialog.SetMsg('Welcome to Pipl Contacts, enjoy browsing your contact book and discovering relevant information about the people (you think) you know.<br/><br/>Please wait while we search through billions of pages for relevant information, this might take a few moments. If you do not wish to wait you may close this window and we will notify you by e-mail when we are done.<br/><br/>This message will disappear as soon as you receive some results.');
		CMDialog.SetLoadingTitle();
		CMDialog.SetCloseButton(false);
		CMDialog.SetWidth(600);
		CMDialog.Show(true);
		jQuery('.ui-dialog-titlebar-close').hide()
		return CMDialog;
	}
	return null;
}

function genThumbUrl(size, imageUrl)
{
	var thumbUrl = 'http://'+hex_md5(imageUrl).substr(0,1)+'.thumb.pipl.com/cgi-bin/fdt.fcgi?QUERY_STRING=hg='+size+'&wd='+size+'&th=1&url='+imageUrl;
	return thumbUrl;
}


function checkEmailValue(input)
{
	input.value = input.value.replace(/\@.*/, '');
}

function QuoteToHTML(source)
{
	return source.replace(/\\"/g, '&quot;').replace(/"/g, '&quot;');
}
function UnSingleQuote(source)
{
	return source.replace(/\\/g, '').replace(/'/g, '\\\'');
}

function DoubleSlashesForHTMLJson(source)
{
	return source.replace(/\\+'/g, '\'').replace(/\\+/g, '\\').replace(/\\/g, '\\\\').replace(/'/g, '\\\'');
}

function HTMLSingleQuotesDecode(source)
{
	return source.replace(/\\/g, '').replace(/'/g, '&#39;');
}

var monthSN = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
      
function stringToDate(string) {
    var matches;
    if (matches = string.match(/^(\d{4,4})-(\d{2,2})-(\d{2,2})$/)) {
      var date = new Date(matches[1], matches[2] - 1, matches[3]);
      if(date)
      {  
	      //var monthFN: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
	      var day = matches[3];
	      var month = monthSN[date.getMonth()];
	      var year = date.getFullYear();
	      return month+' '+day+', '+year;
      }
      else return string;
    } else {
      return string;
    }
};

function dateToString(date) {
    var month = (date.getMonth() + 1).toString();
    var dom = date.getDate().toString();
    if (month.length == 1) month = "0" + month;
    if (dom.length == 1) dom = "0" + dom;
    return date.getFullYear() + "-" + month + "-" + dom;
}

function SetContentHeight()
{
	var docHeight = $.getDocHeight();
	var headerHeihgt = document.getElementById('header').clientHeight;
	var footerHeihgt = document.getElementById('footer').clientHeight;
	var contentHeight = docHeight - headerHeihgt - footerHeihgt - 140;
	var content = document.getElementById('cm_rep_cont_list');
	content.style.maxHeight = contentHeight+'px';
}

function setSource(src, imageId)
{
	var image = document.getElementById(imageId);
	image.src = src;
}

function updateContacts()
{
	var formInputs = $("#cm_cont_list_ccol input:checked");
	if(formInputs.length > 0)
	{
		CMDialog.SetLoadingTitle();
		CMDialog.SetMsg('Your contacts are being updated.');
		CMDialog.SetCloseButton(false);
		CMDialog.Show(true);
		
		var ids = new Array(), id;
		for(var i=0; i < formInputs.length; i++)
		{
			id = '';
			id = formInputs[i].id;
			id = id.substr(18);
			if(id != '') ids.push(id);
		}
		if(ids.length > 0)
		{				
			new $.ajax({
						async: 		true,
						url: 		contactsUrl+'update',
                                                data:           'cont_list='+$.toJSON(ids),
						type:   	'POST',
						error: 		function(XMLHttpRequest)
						{
							if(XMLHttpRequest.status == '302')
							{
								window.location.href = contactsUrl+'login';
							}	
							CMDialog.SetTitle('Error');
							CMDialog.SetMsg('Error uccoured while updating you contacts.<br/>Please try again later');
							CMDialog.SetCloseButton(true);
						},
						success: 	function(response)
						{	
							CMDialog.SetTitle('Success');
							CMDialog.SetMsg('Your contacts were updated successfully.');
							//CMDialog.SetInviteButton(true);
							CMDialog.SetCloseButton(true);
						}
			});
		}
	}	
	else
	{
		CMDialog.SetTitle('Error');
		CMDialog.SetMsg('Please select contacts');
		CMDialog.SetCloseButton(true);
		CMDialog.Show(true);
	}
}

function submit_form(formName)
{
	var contForm = document.getElementById(formName);
	contForm.submit();
}

function onLoadCommands()
{
    var buttonLine = document.getElementById('sub_but_place');
	    var str = '<div id="progressdesc" class="progressdesc"></div>';
	    str += '<div id="loadprogressbar" class="progressbar"></div>';
	    buttonLine.innerHTML = str;
	   
}
/*
function onLoadReportCommands(invNum, invAllowed)
{
	var buttonLine = document.getElementById('sub_but_place');
	var str = '<button type="submit" onclick="validate_form(\'cm_invite_list_from\', \'Please select up tp 3 people to invite\', {invNum : '+invNum+', invAllowed: '+invAllowed+'})" class="submit_but">Invite Selected Contacts</button>';
	buttonLine.innerHTML = str;
	SetContentHeight();
}*/
/*
function initOnLoad()
{
	
	if(Browser.IE)
	{
		window.onload = function() {onLoadCommands();};
	}
	else document.body.setAttribute('onload', 'onLoadCommands()');
}*/

$.getDocHeight = function(){
    return Math.min(
        $(document).height(),
        $(window).height(),
        /* For opera: */
        document.documentElement.clientHeight
    );
};

function changecss(SSName, myclass,element,value) 
{
	return $(myclass).css(element,value);
	/*var CSSRules;
	if (document.all) {
		CSSRules = 'rules';
	}
	else if (document.getElementById) {
		CSSRules = 'cssRules';
	}
	var href = '';
	for (var i = 0; i < document.styleSheets.length; i++) 
	{
		href = document.styleSheets[i].href;
		if(href.indexOf("http:")<0)
		{
			for (var j = 0; j < document.styleSheets[i][CSSRules].length; j++) {
				if (document.styleSheets[i][CSSRules][j].selectorText == myclass) {
					document.styleSheets[i][CSSRules][j].style[element] = value;
				}
			}
                        /*
			break;
		}
	}*/		
}

function getcss(SSName, myclass, element) 
{
    return $(myclass).css(element);
	/*var CSSRules;
	if (document.all) {
		CSSRules = 'rules';
	}
	else if (document.getElementById) {
		CSSRules = 'cssRules';
	}
	var href = '';
	for (var i = 0; i < document.styleSheets.length; i++) 
	{
		href = document.styleSheets[i].href;
		if(href.indexOf("http:")<0)
		{
			for (var j = 0; j < document.styleSheets[i][CSSRules].length; j++) {
				if (document.styleSheets[i][CSSRules][j].selectorText == myclass) {
					return document.styleSheets[i][CSSRules][j].style[element];
				}
			}
                        /*
			break;
		}
	}	*/	
}

function RemoveQuotes(source)
{
	return source.replace(/'/g, '').replace(/"/g, '');
}

function select_all(selAll, cb_place)
{	
	var isChecked = (selAll) ? selAll.checked : false;
	var formInputs = $('#'+cb_place+' :checkbox').each(function(){
		if(this.nextSibling){
			if(this.nextSibling.nextSibling)
			{
				if(this.nextSibling.nextSibling.onclick) this.checked = isChecked;
			}
		}
	});
}

/*
function findPositionWithScrolling( oElement ) 
{
  if( typeof( oElement.offsetParent ) != 'undefined' ) 
  {
    var originalElement = oElement;
    for( var posX = 0, posY = 0; oElement; oElement = oElement.offsetParent ) 
    {
      posX += oElement.offsetLeft;
      posY += oElement.offsetTop;
      if( oElement != originalElement && oElement != document.body && oElement != document.documentElement ) 
      {
        posX -= oElement.scrollLeft;
        posY -= oElement.scrollTop;
      }
    }
    return [ posX, posY ];
  } 
  else 
  {
    return [ oElement.x, oElement.y ];
  }
}*/

function fixedEncodeURIComponent (str) {  
	return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');  
}  

function findPositionWithScrolling( oElement ) 
{
	  function getNextAncestor( oElement ) 
	  {
		    var actualStyle;
		    if( window.getComputedStyle )
		    {
		      actualStyle = getComputedStyle(oElement,null).position;
		    } 
		    else if( oElement.currentStyle ) 
		    {
		      actualStyle = oElement.currentStyle.position;
		    } 
		    else 
		    {
		      //fallback for browsers with low support - only reliable for inline styles
		      actualStyle = oElement.style.position;
		    }
		    if( actualStyle == 'absolute' || actualStyle == 'fixed' ) 
		    {
		      //the offsetParent of a fixed position element is null so it will stop
		      return oElement.offsetParent;
		    }
		    return oElement.parentNode;
	  }
	  if( typeof( oElement.offsetParent ) != 'undefined' ) 
	  {
		    var originalElement = oElement;
		    for( var posX = 0, posY = 0; oElement; oElement = oElement.offsetParent ) 
		    {
		      posX += oElement.offsetLeft;
		      posY += oElement.offsetTop;
		    }
		    if( !originalElement.parentNode || !originalElement.style || typeof( originalElement.scrollTop ) == 'undefined' ) 
		    {
		      //older browsers cannot check element scrolling
		      return [ posX, posY ];
		    }
		    oElement = getNextAncestor(originalElement);
		    while( oElement && oElement != document.body && oElement != document.documentElement ) 
		    {
		      posX -= oElement.scrollLeft;
		      posY -= oElement.scrollTop;
		      oElement = getNextAncestor(oElement);
		    }
		    return [ posX, posY ];
	  } 
	  else 
	  {
		  	return [ oElement.x, oElement.y ];
	  }
}

function addClickEvent(_elem, _evtName, contId, serviceId, email, name, serviceInfo, matchesInfo, _useCapture)
{
	var _fn = function(e){ 
		var theTarget = e.target ? e.target : e.srcElement;
		CONTMATE.ShowContact(theTarget, contId, serviceId, email, name, serviceInfo, matchesInfo);
		return LettersMenu.CheckCB(theTarget);
	};
	if (typeof _elem.attachEvent != 'undefined')
   {
	   _elem.attachEvent('on' + _evtName, _fn, _useCapture);
   }
   else
   {
	   _elem['on' + _evtName] = _fn;
   }
}

function addClickCheckBoxEvent(_elem, _evtName, categoryId, itemNum, uniqueId, _useCapture)
{
	var _fn = function(e){ 
		var theTarget = e.target ? e.target : e.srcElement;
		CONTMATE.ShowContact(theTarget, categoryId, itemNum, uniqueId, matchesInfo);
	};
	if (typeof _elem.attachEvent != 'undefined')
   {
	   _elem.attachEvent('on' + _evtName, _fn, _useCapture);
   }
   else
   {
	   _elem['on' + _evtName] = _fn;
   }
}


/*
 * code was take from
 * http://blog.stchur.com/2007/03/15/mouseenter-and-mouseleave-events-for-firefox-and-other-non-ie-browsers/
 * you can find a good explanation to whats going on here.
 */
function addEvent(_elem, _evtName, _fn, _useCapture)
{
   if (typeof _elem.addEventListener != 'undefined')
   {
      if (_evtName === 'mouseenter')
         {_elem.addEventListener('mouseover', mouseEnter(_fn), _useCapture);}
      else if (_evtName === 'mouseleave')
         {_elem.addEventListener('mouseout', mouseEnter(_fn), _useCapture);}
      else
         {_elem.addEventListener(_evtName, _fn, _useCapture);}
   }
   else if (typeof _elem.attachEvent != 'undefined')
   {
      _elem.attachEvent('on' + _evtName, _fn);
   }
   else
   {
      _elem['on' + _evtName] = _fn;
   }
}

function mouseEnter(_fn)
{
   return function(_evt)
   {
      var relTarget = _evt.relatedTarget;
      if (this === relTarget || isAChildOf(this, relTarget))
         {return;}

      _fn.call(this, _evt);
   };
};

function isAChildOf(_parent, _child)
{
   if (_parent === _child) {return false;}
      while (_child && _child !== _parent)
   {_child = _child.parentNode;}

   return _child === _parent;
}

function imagePreLoader() 
{
	var imagesNames = new Array('close_x', 'stat_change_bg', 'accept_click', 'accept_flat', 'accept_hover', 'maybe_flat', 'maybe_click', 'maybe_hover', 'reject_flat', 'reject_click', 'reject_hover');
	for(var i=0; i < imagesNames.length; i++)
	{
		preImage = new Image(); 
		preImage.src = DIR_PIPL_ASSETS_BUTTON+imagesNames[i]+'.png';
		delete preImage;
	}	
}

/*
function SetStatusImage(element, contId, match, catId, uniqueId, itemNum)
{
	switch(match)
	{
		case MATCH_REJECTED: 				element.src = DIR_PIPL_ASSETS_BUTTON+'reject_flat.png';
											break;
		case MATCH_ACCEPTED:				element.src = DIR_PIPL_ASSETS_BUTTON+'accept_flat.png';
											break;	
		default: 							element.src = DIR_PIPL_ASSETS_BUTTON+'maybe_flat.png';		
	}
	element.onmouseover = new Function('PopStatusChanger(\''+contId+'\', \''+match+'\', \''+catId+'\', \''+uniqueId+'\', \''+itemNum+'\')');	
}*/

function RemoveNode(object)
{
	object.parentNode.removeChild(object);
}

function HtmlDecodeB(source)
{
	return source.replace(/&lt;b&gt;/g, '<b>').replace(/&lt;\/b&gt;/g, '</b>');
}

function ShowAssetDirContent(contId, type)
{
	CONTMATE.ContAssetsBuilder.ShowCatContent(contId, type);
}

function PopStatusChanger(contId, match, catId, uniqueId, personNum)
{
	CONTMATE.ContAssetsBuilder.ShowStatusPopUp(contId, match, catId, uniqueId, personNum);
}

function hideStatusChanger()
{
	CONTMATE.ContAssetsBuilder.HideStatusPopUp();
}

 function doLoginEmailWatch() {
      jQuery("#login_options > li").hide();
      jQuery("#loginform .continue").show();
      $.each(providers, function(i,provider) {
	  $.each(provider.domains, function(j,domain) {
	      var pattern =new RegExp( '[^@]+@'+domain+'\.[0-9a-z]{2,4}');
	      if(jQuery("#login_email").val().toLowerCase().match(pattern)){
		  jQuery("#loginform .continue").hide();
		if(provider.login.provider) {
		    jQuery("#login_options .provider").show();
		    jQuery("#login_options .provider > div").removeClass().addClass('provider-'+i);
		}
		if(provider.login.direct) jQuery("#login_options .direct").show();
		if(provider.login.direct && provider.login.provider) jQuery("#login_options .or").show();
	      }
	  })
      });
  }
