String.prototype.trim = function() { return this.replace(/^\s+|\s+$/gim, ''); };

function downloadPlugin(anchor) {
   var url = '/plugin/ib.xpi';
   if (document.all) 
     url = '/plugin/IB_Installer.exe';
   if (anchor) {
     anchor.href = url;
   } else {
     window.location = url;
   }
   return true;
}

function buttonMouseOver(el) {
  if(el.src.indexOf('_over') > 0) return;
  el.src = el.src.substring(0, el.src.length - 4) + '_over' + '.' + el.src.substring(el.src.length - 3);
}
function buttonMouseOut(el) {
  if(el.src.indexOf('_over') < 0) return;
  el.src = el.src.substring(0, el.src.length - 9) + '.' + el.src.substring(el.src.length - 3);
}

var footerAdjust = 40;
var disableFooterAdjust = false;
function repositionFooter() {
  if (disableFooterAdjust) return;
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  
  var element = document.getElementById('content');
  if (element) {
    element.style.height = "auto";
    var offset = Position.cumulativeOffset(element);
    var height = element.offsetHeight;
    if (myHeight-footerAdjust > offset[1]+height) {
      element.style.height = (height + (myHeight-height-offset[1]-footerAdjust))+"px";
    }
  }
}

function validateTextField(field, msg) {
  if ($(field) && $(field).value.trim() == '') {
    $(field).focus();
    alert("Please enter "+msg);
    return false;
  }
  return true;
}

function validEmail(input) {
  var emailReg = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
  var regex = new RegExp(emailReg);
  return regex.test(input);
}

function validateShare() {
  var frm = $('shareIncident');
  if (!validEmail(frm.email.value)) {
    alert("Please enter a valid email address");
    return false;
  }
  return true;
}

function showProgress(id) {
  if ($(id)) {
    $(id).innerHTML = '<img src="/images/progress_black.gif"/>';
  }
}

function toggleDisplay() {
	for (var i=0;i<arguments.length;i++) {
		if (typeof(arguments[i]) == 'string')
	    	var element = document.getElementById(arguments[i]);
	    else
	    	var element = arguments[i];
		if (element) {
			if (element.style.display == "none")
				element.style.display = "";
			else
				element.style.display = "none";
		}
	}
	repositionFooter();
}

function watchChangeDone(chkBox, companyId, progId) {
  $(progId).hide();
  $(chkBox).show();
  if (typeof(window.watchChangedHandler) == 'function') {
    window.watchChangedHandler();
  }
  updateCompanyWatchStatus(chkBox.getAttribute('company'), chkBox.checked);
}

function updateCompanyWatchStatus(companyId, checked) {
  var inputs = document.getElementsByTagName('input');
  for (var i=0;i<inputs.length;i++) {
    if (inputs[i].type.match(/checkbox/i) && inputs[i].getAttribute('company') == companyId) {
      inputs[i].checked = checked;
    } 
  }
}

function informPlugin(domain, relation) {
  if (!pluginInstalled) return;
  var exdate=new Date();
  exdate.setDate(exdate.getDate()+365);
  window.location = "/ib_access/setDomainCookie/ibw="+relation+";expires="+exdate.toGMTString()+"/"+domain;
}

function watchChangeStarted(chkBox, companyId, progId) {
  $(chkBox).hide();
  showProgress(progId);
}

function addWatch(companyId, progId) {
  var chkBox = $('chk'+progId);
  chkBox.checked = !chkBox.checked;
  watchChanged(chkBox, companyId, progId)
}

function watchChanged(chkBox, companyId, progId) {
  if (chkBox.checked) {
    var url = '/watchlist/add?company_id='+companyId;
    urchinTracker('/watchlist/add');
  } else {  
    var url = '/watchlist/delete?company_id='+companyId;
    urchinTracker('/watchlist/delete');
  }
  if (document.location.href.indexOf('frontend_dev')!=-1) url = "/frontend_dev.php"+url;
  new Ajax.Updater(progId, url, {asynchronous:true, evalScripts:true, onLoading:function(request, json){watchChangeStarted(chkBox, companyId, progId);}, onComplete:function(transport){setTimeout(function(){watchChangeDone(chkBox, companyId, progId);}, 500);}});
}


function showDhtmlPopup(name, title, url, width, height) {
  var win = Windows.getWindow(name);
  if (!win) {
    win = new Window(name, {className: "mac_os_x",  zIndex: 100, width:width, height:height, resizable: true, title: title, draggable:true, minimizable:false, maximizable:false});
  }
  showProgress(win.getContent());
  win.setDestroyOnClose();
  win.setAjaxContent(url, {method:'get'}, false);
  win.showCenter(true);
  return false;
}

function addNewCompany(url) {
  return showDhtmlPopup('newCompanyWin', "Add a new company", url, 350, 200);
}

function showLogin(title, targetUrl) {
  title = (typeof(title) == 'undefined')?'Login/Register':title; 
  targetUrl = (typeof(targetUrl) == 'undefined')?'':'?target='+targetUrl; 
  return showDhtmlPopup('loginWin', title, '/user/login'+targetUrl, 350, 250);
}

function switchTab(newTab) {
  var current = document.getElementById(newTab);
  while (current && current.nodeName.toLowerCase() != 'ul') {
    current = current.parentNode;
  }
  if (current) {
    var links = current.getElementsByTagName("a");
    for (var i=0;i<links.length;i++) {
      var id = links[i].getAttribute('id');
      var content = document.getElementById(id+"Contents");
      if (id == newTab) {
          if (links[i].className.indexOf("active") >= 0) return true;
          links[i].className = links[i].className.replace(/[\s]*active/gim, '')+' active';
          if (content) content.style.display = "";
      } else {
          links[i].className = links[i].className.replace(/[\s]*active/gim, '');
          if (content) content.style.display = "none";
      }
    }
  }
  repositionFooter();
  return false;
}

var _ib_domain = 'www.identitybreach.com';
 
function __ibIsPlugin() {
  return false;
};

function IB_GetCookie(name) {
  return 'n';
}

function __ibSetDomainCookie(doc, name, value) {
}

function __ibGetDomainCookie(doc, name) {
  if (typeof(window.ibWatched) != 'undefined' && name=='ibw') {
     return window.ibWatched;
  }
  return '';
}

function __ibAddEventHandler(element, eventName, handler) {
  Event.observe(element, eventName, handler);
}

function sendToIBWindow(pageUrl, script, setfocus, callback) {
}

function highlightElement(id, times) {
  if (!$(id) || $(id).getAttribute('inProgress') == "true") return;
  $(id).setAttribute("inProgress","true");
  new Effect.Highlight(id);
  var wait = 0;
  for(var i=0;i<times-1;i++) {
     wait += 2000;
     setTimeout(function(){new Effect.Highlight(id);}, wait);
  }
  setTimeout(function(){$(id).setAttribute("inProgress","");}, wait+2000);
}
function toggleAddNewCompanyForm(msg) {
  if (typeof(msg) != 'undefined') {
	if ($('search').value == $('search').getAttribute('info')) {
		$('search').value = '';
	}
	$('search').setAttribute('info', msg);
	setupInfoField('search');
  }
  $('newWatchForm').show();
  if ($('newWatchForm').style.display == '') {
    Effect.Pulsate('search');
  }
}

function stateCheckChanged(chkBox) {
  if (chkBox.checked) {
    $('num_affected_'+chkBox.value).removeAttribute('disabled');
    $('num_affected_'+chkBox.value).style.display = '';
  } else {
    $('num_affected_'+chkBox.value).setAttribute('disabled', 'disabled');
    $('num_affected_'+chkBox.value).style.display = 'none';
  }
}

function showCraNotification(detailId) {
  return showDhtmlPopup('craWin', "CRA Notification Preview", '/notify/cra?id='+detailId, 500, 400);
}

function showAgNotification(detailId) {
  return showDhtmlPopup('agWin', "AG Notification Preview", '/notify/ag?id='+detailId, 500, 400);
}

function craChanged(selBox, detailId) {
  var craId = selBox.options[selBox.selectedIndex].value;
  selBox.form.submit();
}

function urchinTracker(url){
  if (typeof(pageTracker) != 'undefined' && pageTracker) 
     pageTracker._trackPageview(url);
}

function urchinLinkoutTracker(anchor){
  if (typeof(pageTracker) != 'undefined' && pageTracker && anchor) 
     pageTracker._trackPageview(anchor.getAttribute('href'));
}


function slideUpEffect(elementId, afterFinishFn) {
    if (typeof(afterFinishFn) == "function")
        new Effect.SlideUp(elementId, {afterFinish:afterFinishFn});
    else
        new Effect.SlideUp(elementId);
}

function slideDownEffect(elementId, afterFinishFn) {
    if (typeof(afterFinishFn) == "function")
        new Effect.SlideDown(elementId, {afterFinish:afterFinishFn});
    else
        new Effect.SlideDown(elementId);
}

function infoBoxFocus(elementId) {
    var element = $(elementId);
    if (element.value == element.getAttribute("info")) {
        element.value = "";
        element.removeClassName("infoText");
    } else 
        element.select();
}

function infoBoxBlur(elementId) {
    setupInfoField(elementId);
}

function clearInfoFields(frmName) {
    var frm = $(frmName);
    for (var i=0;i<frm.elements.length;i++) {
        clearInfoField(frm.elements[i]);
    }
}

function clearInfoField(element) {
    var element = $(element);
    if (element.type == "text" && element.value == element.getAttribute("info"))
        element.value = "";
}

function initInfoField(elementId) {
    var element = $(elementId);
    Event.observe(element, "focus", function(){infoBoxFocus(elementId);}); 
    Event.observe(element, "blur", function(){infoBoxBlur(elementId);});
    setupInfoField(elementId);
}
function setupInfoField(elementId) {
    var element = $(elementId);
    if (element.value == "" || element.value == element.getAttribute("info")) {
      element.value = element.getAttribute("info");
      element.addClassName("infoText");
    } else {
      element.removeClassName("infoText");
    }
}

function animateProgress(id, delay, value, afterDone) {
  $(id).style.width = Math.round(value)+"%";
  if (value == 100) {
    afterDone();
  } else {
    setTimeout(function(){animateProgress(id, delay, value+20, afterDone)}, delay);
  }
}

function validateDefaultForm() {
  
  return true;
}

function showSlide(idx) {
  var images = ["BusinessWoman.jpg", "FashionGirl.jpg", "AngryBoy.jpg"];
  var messages = ['<big><p><span style="color:#333399">"I can\'t believe my bank got hacked and my identity\'s out there now"</span></p><br/>Karen Linwood, Detroit MI</big>','<big><p><span style="color:#333399">"I feel better entering my personal info online now that I can monitor it"</span></p><br/>Tina K - Boston, MA</big>', '<big><p><span style="color:#333399">"I signed up to play this video game online.  Now someone\'s using my identity?"</span></p><br/>Lance Butler - Oakland, CA</big>'];
  $('slidePicture').src = "/images/"+images[idx];
  $('slideMessage').innerHTML = messages[idx];
  idx++;
  if (idx >= images.length) idx = 0;
  repositionFooter();
  setTimeout(function(){showSlide(idx)}, 10000); 
}

function toggleRelationship(watchId) {
  toggleDisplay('relation_edit_'+watchId, 'relation_view_'+watchId); 
}

function saveRelationship(watchId) {
  var relation = $('relation_'+watchId).options[$('relation_'+watchId).selectedIndex].value;
  $('relation_label_'+watchId).innerHTML = relation;
  toggleRelationship(watchId);
  new Ajax.Updater('blank', '/dashboard/saveRelation?id='+watchId+'&type='+escape(relation), {asynchronous:true, evalScripts:true});
}

function goToPage(formName, pageName, page) {
  $(pageName).value = page;
  $(formName).submit();
}

function isUpClicked(newsId) {
    return $("up_"+newsId).src.indexOf("upvote") >= 0;
}
function isDownClicked(newsId) {
    return $("down_"+newsId).src.indexOf("downvote") >= 0;
}
function upClicked(newsId) {
  new Ajax.Updater("vote_"+newsId, '/news/vote?id='+newsId+'&vote='+(isUpClicked(newsId)?0:1), {asynchronous:true})
  $("up_"+newsId).src = isUpClicked(newsId)?"/images/upnovote.gif":"/images/upvote.gif";
  $("down_"+newsId).src = "/images/downnovote.gif";
  $("up_"+newsId).blur();
  return false;
}

function downClicked(newsId) {
  new Ajax.Updater("vote_"+newsId, '/news/vote?id='+newsId+'&vote='+(isDownClicked(newsId)?0:-1), {asynchronous:true})
  $("down_"+newsId).src = isDownClicked(newsId)?"/images/downnovote.gif":"/images/downvote.gif";
  $("up_"+newsId).src = "/images/upnovote.gif";
  $("down_"+newsId).blur();
  return false;
}

function validMessage(form) {
  if ($(form).body.value.trim() == '') {
    alert("Please enter valid message");
    return false;
  }
  return true;
}

function togglePostForm(target, parent) {
  var div = $('discussionForm');
  if (div.parentNode.id != target) {
	div.parentNode.hide();
	div.parentNode.removeChild(div);
	$(target).appendChild(div);
  }
  var frm = $('composeForm');
  frm.parentId.value = parent;
  frm.body.value = '';
  $('cancelBtn').onclick = function(){togglePostForm(target, parent)};
  $(target).toggle();
  repositionFooter();
  if ($(target).visible())
    setTimeout(function(){$('cancelBtn').scrollIntoView(false);frm.body.focus();}, 200);
}

function validateNewsForm() {
  var frm = $('newsForm');
  if (frm.title.value.trim() == '') {
    alert('Please enter title');
    return false;
  }
  if (frm.url.value.trim() == '') {
    alert('Please enter url');
    return false;
  }
  return true;
}

function incorrectCompany(link, watchId, search) {
  link.parentNode.removeChild(link);
  new Ajax.Updater('myWatchList', '/dashboard/deleteWatchlist/id/'+watchId+'/search/'+search, {asynchronous:true, evalScripts:true});
}

function openInfoDialog() {
	Dialog.info("", {width :350, height :100, showProgress :false});
	infoTimeout(5);
}

function infoTimeout(timeout) {
	timeout--;
	if (timeout > 0) {
		var clearImg = '<img src="/images/tick_clear.gif" class="vm"/>';
		var checkImg = '<img src="/images/tick_checked.gif" class="vm"/>';
		var html = 'Finding company... ';
		if (timeout == 4) html += clearImg;
		if (timeout <= 3) html += checkImg+'<br/><br/>Checking data breaches with identity theft risks...';  
		if (timeout == 3) html += clearImg;
		if (timeout <= 2) html += checkImg+'<br/><br/>Creating your personal security list...';
		if (timeout == 2) html += clearImg;
		if (timeout == 1) html += checkImg;
		Dialog.setInfoMessage('<div style="color:black;font-size:10pt;" class="al vm">'+html+'</div>');
		setTimeout(function(){infoTimeout(timeout)}, 800);
	} else {
		$('searchBox').submit();
		Dialog.closeInfo();
	}
}

function searchFromHome() {
  clearInfoFields($('searchBox'));
  if ($('search').value.trim() == '') {
	  alert("Please enter company name to search.");
	  return false;
  }
  openInfoDialog();
  return false;
}

function showSearchCompanyForDefaultAlert(link, id) {
	$(link).hide();
	$('alertSearch'+id).show();
	initInfoField("search"+id);
}

function searchCompanyForDefaultAlert(id) {
	clearInfoField('search'+id);
	if ($('search'+id).value.trim() =='') {
		alert("Please "+$('search'+id).getAttribute("info"));
		return;
	}
	$('alertId').value = id;
	$('search').value = $('search'+id).value;
	$('searchBox').submit();
}
