﻿//Common functions
//Browser Related/////////////////////////////////////////////////////////////////////////////////////////////////////////
var isMac = new RegExp('(^|)'+'Apple'+'(|$)');  

function isIE()
{
  return /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);
}

function getQueryStringValue(ji) {
 hu = window.location.search.substring(1);
 gy = hu.split("&");
 for (i=0;i<gy.length;i++) {
  ft = gy[i].split("=");
  if (ft[0] == ji) {
   return ft[1];
  }
 }
}

function clearfield(e){
if(isMac.test(navigator.vendor)) {
  e.style.background = '#363636';
}
  e.value = '';
}

function resetfield(e, resetText){
if(isMac.test(navigator.vendor)) {
  e.style.background = '#000';
}
if(e.value==''){e.value=resetText};
}

function uncache(url){
return url + "&uncache=" + new Date().getTime();
}

//String Related/////////////////////////////////////////////////////////////////////////////////////////////////////////
function trimAll(sString) 
{
    while (sString.substring(0,1) == ' ')
    {
        sString = sString.substring(1, sString.length);
    }
    while (sString.substring(sString.length-1, sString.length) == ' ')
    {
        sString = sString.substring(0,sString.length-1);
    }
    return sString;
}    

//OPACITY RELATED FUNCTIONS///////////////////////////////////////////////////////////////////////////////////////////////
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 + ")";
}

function shiftOpacity(id, millisec) {
	//if an element is invisible, make it visible, else make it ivisible
	if(document.getElementById(id).style.opacity == 0) {
		opacity(id, 0, 100, millisec);
	} else {
		opacity(id, 100, 0, millisec);
	}
}

function blendimage(divid, imageid, imagefile, millisec) {
	var speed = Math.round(millisec / 100);
	var timer = 0;
	
	//set the current image as background
	document.getElementById(divid).style.backgroundImage = "url(" + document.getElementById(imageid).src + ")";
	
	//make image transparent
	changeOpac(0, imageid);
	
	//make new image
	document.getElementById(imageid).src = imagefile;

	//fade in image
	for(i = 0; i <= 100; i++) {
		setTimeout("changeOpac(" + i + ",'" + imageid + "')",(timer * speed));
		timer++;
	}
}

function currentOpac(id, opacEnd, millisec) {
	//standard opacity is 100
	var currentOpac = 100;
	
	//if the element has an opacity set, get it
	if(document.getElementById(id).style.opacity < 100) {
		currentOpac = document.getElementById(id).style.opacity * 100;
	}

	//call for the function that changes the opacity
	opacity(id, currentOpac, opacEnd, millisec)
}

//General Functionality related functions/////////////////////////////////////////////////////////////////////////////
function CheckSearchPage(x)
{
 if (x.value.length != 0) 
    {
        if (chkNumeric(x.value) == false) 
        {
            alert("Please check - non numeric value!");
        }
    }else{
        resetfield(x,'Go to page')
    }
}

function OnKeyPressValidateAndGoToPage(e,txtPageNum,actionButton)
{
  if (e.which || e.keyCode)
  {
    if ((e.which == 13) || (e.keyCode == 13))
    {
      var userinput = null;
      userinput = document.getElementById(txtPageNum).value;

      if (userinput != null || userinput != '')
      {
        // We have the value entered in the input field, so let's check it
        if (!chkNumeric(userinput))
        {
          alert("Please check - non numeric value!");
          return false;
        }
      }
      else
      {
        // We don't really have a value in the input field, so there is nowhere to go
        return false;
      }
     
      // We are about to go to some page
      __doPostBack(actionButton,'');
      return true;
    }
  }
}


function chkNumeric(strString)
{
 var numcheck = /\d/;
 if (!numcheck.test(strString))
   {
    return false;
   }
 else
  {
    return true;
  }
}


function RememberMeAlert(pCheckBoxId)
{
  var e = $get(pCheckBoxId);
  
  if (!e.checked)
  {
    return;
  }
  else
  {
    var ok = confirm('WARNING: If you are at a public terminal, we highly recommend that you do not check this box. Only check this box if you are at a secured workstation.');
    
    if (!ok)
    {
      SetAapCheckBoxChecked(e, false);
    }
  }
}

function CheckLoginValues(usernameCtlID, pwdCtlID)
{    
    username = document.getElementById(usernameCtlID);
    pwd = document.getElementById(pwdCtlID);
    if (trimAll(username.value) == "")
    {
        alert("Please Enter Username");
        username.value = trimAll(username.value);
        username.focus();
        return false;
    }else if (trimAll(pwd.value)=="")
    {
        alert("Please Enter Password");
        pwd.value = trimAll(pwd.value)
        pwd.focus();
        return false;
    }else
    {
        if (document.getElementById('HomepageImage')){
          stopTimer();
        }
        return true;
    }
}


//Popup////////////////////////

function newWindow(mypage,myname,w,h,features) {
  var win = null;
  var winl = (screen.width-w)/2;
  var wint = (screen.height-h)/2;
  if (winl < 0) winl = 0;
  if (wint < 0) wint = 0;
  var settings = 'height=' + h + ',';
  settings += 'width=' + w + ',';
  settings += 'top=' + wint + ',';
  settings += 'left=' + winl;
  settings += features;
  win = window.open(mypage,myname,settings);
  win.focus();
}


//AJAX related//////////////////////////////////////////////////////////////////////////////////////////////////////////////

//AJAX related functions used by Home.aspx////////////////////////

function requestStartHomePage(sender, eventArgs)
{
   var Currentevent = eventArgs.get_eventTarget();
    if(Currentevent == 'ImageChangeTimer'){
    if (document.getElementById('HomepageImage')){
    changeOpac(100,"HomepageImage");
    opacity('HomepageImage', 100, 0, 500);
    }
    }
}

function responseEndHomePage(sender, eventArgs)
{
    var Currentevent = eventArgs.get_eventTarget();
    if(Currentevent == 'ImageChangeTimer'){
    if (document.getElementById('HomepageImage')){
    changeOpac(0,"HomepageImage");
    opacity('HomepageImage', 0, 100, 500);
    }
    }
}

function ShowCaption(id){
    opacity(id, 0, 70, 500);
    stopTimer();
}
      
      
function HideCaption(id){
    opacity(id, 70, 0, 500);
    startTimer();
}


//
// Ajax Related functions used by Lightbox Control////////////////////////
//

function GetPopupWindowParameters(pGapWidth, pGapHeight)
{
  var CurrentLightBox;
  var lightBoxWindowWidth = (screen.width - pGapWidth);
  var lightBoxWindowHeight = (screen.height - pGapHeight);
  var lightBoxWindowTop = (screen.height - lightBoxWindowHeight)/2;
  var lightBoxWindowLeft = (screen.width - lightBoxWindowWidth)/2;
  var lightBoxWindowParameters = 
    'width=' + lightBoxWindowWidth + 
    ',height=' + lightBoxWindowHeight + 
    ',top=' + lightBoxWindowTop + 
    ',left=' + lightBoxWindowLeft + 
    ',scrollbars=yes' + 
    ',resizable=yes';

  return lightBoxWindowParameters;
}

function responseEndMaster(sender, eventArgs)
{
  var Currentevent = eventArgs.get_eventTarget();
  var lightBoxWindowParameters = GetPopupWindowParameters(100, 270);
  
  if (document.getElementById('lightbox_CurrentLightBoxAlbumID'))
  {
    CurrentLightBox = document.getElementById('lightbox_CurrentLightBoxAlbumID').value
  };
  
  if (document.getElementById('ctl00_UcSide_lightbox_CurrentLightBoxAlbumID'))
  {
    CurrentLightBox = document.getElementById('ctl00_UcSide_lightbox_CurrentLightBoxAlbumID').value
  };
  
  if (Currentevent == 'ctl00$UcSide$lightbox$btnSearch')
  {
    window.open('LightBox.aspx?AlbumID=' + CurrentLightBox,'LightBox', lightBoxWindowParameters);
    
    if (document.getElementById('ctl00_UcSide_lightbox_LightBoxMessage'))
    {
      document.getElementById('ctl00_UcSide_lightbox_LightBoxMessage').innerHTML = '';
    }
  }
  
  if (Currentevent == 'lightbox$btnSearch')
  {
    window.open('LightBox.aspx?AlbumID='+ CurrentLightBox,'LightBox', lightBoxWindowParameters);
    
    if (document.getElementById('lightbox_LightBoxMessage'))
    {
      document.getElementById('lightbox_LightBoxMessage').innerHTML = '';
    }
  }
}

function responseEventsLightBoxControl(){
  if(document.getElementById('lightbox_LightBoxcomboUpdate')){
    __doPostBack('lightbox$LightBoxcomboUpdate','');
  }
  if(document.getElementById('ctl00_UcSide_lightbox_LightBoxcomboUpdate')){
    __doPostBack('ctl00$UcSide$lightbox$LightBoxcomboUpdate','');
  } 
  if(document.getElementById('lightbox_txtAlbumName')){
  document.getElementById('lightbox_txtAlbumName').value = '[Add a New Lightbox]';
  }
  if(document.getElementById('ctl00_UcSide_lightbox_txtAlbumName')){
  document.getElementById('ctl00_UcSide_lightbox_txtAlbumName').value = '[Add a New Lightbox]';
  }
}


//AJAX related functions used by Lightbox.aspx////////////////////////

function LightBoxEventsStart(sender, eventArgs)
{
  if ((window.opener) && (window.opener.document))
  {
    if (window.opener.document.getElementById('lightbox_ddlLightBoxToOpen_Input')){window.opener.document.getElementById('lightbox_ddlLightBoxToOpen_Input').value = document.getElementById('ddlLightBoxToOpen_Input').value};
    if (window.opener.document.getElementById('ctl00_UcSide_lightbox_ddlLightBoxToOpen_Input')){window.opener.document.getElementById('ctl00_UcSide_lightbox_ddlLightBoxToOpen_Input').value = document.getElementById('ddlLightBoxToOpen_Input').value};

    //    if ((window.opener.opener) && (window.opener.opener.document))
    //    {
    //      if (window.opener.opener.document.getElementById('lightbox_ddlLightBoxToOpen_Input')){window.opener.opener.document.getElementById('lightbox_ddlLightBoxToOpen_Input').value = document.getElementById('ddlLightBoxToOpen_Input').value};
    //      if (window.opener.opener.document.getElementById('ctl00_UcSide_lightbox_ddlLightBoxToOpen_Input')){window.opener.opener.document.getElementById('ctl00_UcSide_lightbox_ddlLightBoxToOpen_Input').value = document.getElementById('ddlLightBoxToOpen_Input').value};
    //    }
  }
}

function LightBoxEventsEnd(sender, eventArgs)
{
  var Currentevent = eventArgs.get_eventTarget();
  var updateParentWindowCurrentLightBox = ((Currentevent == 'btnDeleteLightBox') || (Currentevent == 'btnOpenLightBox'));
  
  if (Currentevent == 'btnDeleteLightBox')
  {
    var canDeleteLightBoxes = null;
    
    if($get('hdnShowDeleteLightBoxPanel'))
    {
      canDeleteLightBoxes = Boolean.parse($get('hdnShowDeleteLightBoxPanel').value);
    }
    
    var btnDel = $get('delBtn');
    
    if (btnDel != null)
    {
      $get('delBtn').style.display = 'block';
    }
    
    var msgDel = $get('delMsg');
    
    if (msgDel != null)
    {
      $get('delMsg').style.display = 'none';
    }
    
    if(!canDeleteLightBoxes)
    {
      $get('pnlDeleteLightBox').style.display = 'none';
    }
    else
    {
      $get('pnlDeleteLightBox').style.display = 'block';
    }
  }
  
  if (updateParentWindowCurrentLightBox)
  {
    if (window.opener.$get('lightbox_LightBoxcomboUpdate'))
    {
      window.opener.__doPostBack('lightbox$LightBoxcomboUpdate','');
    }
    
    if (window.opener.$get('ctl00_UcSide_lightbox_LightBoxcomboUpdate'))
    {
      window.opener.__doPostBack('ctl00$UcSide$lightbox$LightBoxcomboUpdate','');
    }
  }
}

 // This function is used because firefox refuses to assign the value of checked property to checkbox input element in javascript
 function SetAapCheckBoxChecked(pCheckBox, pChecked)
 {
	 pCheckBox.defaultChecked = pChecked; // remove this and it won't work in Firefox
	 pCheckBox.checked = pChecked;
	 pCheckBox.nextSibling.className = ((pChecked) ? "ImageSkin rfdCheckboxChecked" : "ImageSkin rfdCheckboxUnchecked"); // remove this and it won't work in Safari
	 return;
 };
 
// 
// Get Selected/Marked Images As a String of Comma-Separated IDs.
//
function GetSelectedImages(pCheckBoxId)
{
  var inputElements = document.getElementsByTagName("INPUT");
  var selectedImages = ''; 
  
  for (i=0; i<inputElements.length; i++)
  {
    var e = inputElements[i];
    
    if (e.getAttribute("type").toLowerCase() == "checkbox" && (e.id.indexOf('cbCellCheckBox') != -1)) 
    {
     if (e.checked)
      {
        selectedImages += ((selectedImages == '') ? '' : ',') + e.value;
      }
    } 
  }
  return selectedImages;
}


//AJAX related functions used  on Search.aspx////////////////////////
function HandleAddImageToLightBoxByImageId(pImageId)
{
  var currentLightBoxAlbumId = '';
  
  if ($find('ctl00_UcSide_lightbox_ddlLightBox'))
  { 
    currentLightBoxAlbumId = $find('ctl00_UcSide_lightbox_ddlLightBox').get_value()
  }

  var w = window.open(uncache('LightBox.aspx?ItemToAdd=' + pImageId) + '&AlbumID=' + currentLightBoxAlbumId, 'LightBox', GetPopupWindowParameters(165, 270));
  w.focus();
}

function HandleAddImageToLightBox(pCheckBoxId)
{
  var CheckBoxPassed = $get(pCheckBoxId);

  if (CheckBoxPassed)
  {
    SetAapCheckBoxChecked(CheckBoxPassed, true);
  }

  var ImageId = GetSelectedImages('');
  
  // Display Status overlay
  var overlay = document.getElementById('overlay');
  var resultContainer = document.getElementById('searchResults');
  var resultTable =  document.getElementById('ctl00_here_Table1');
  var loadingText = document.getElementById('loadingText');
  var ImagesToAddHiddenField = $get('ctl00_here_hfSelectedImages');
  
  if (overlay && resultContainer && loadingText)
  {
    overlay.style.display = 'block';
    overlay.style.width = resultContainer.offsetWidth;
    overlay.style.height = resultContainer.offsetHeight;
  }
  
  if (resultTable)
  {
    loadingText.style.marginLeft = (resultTable.offsetWidth / 2) - 100;
  }
  else if (overlay)
  {
    loadingText.style.marginLeft = (overlay.offsetWidth / 2) - 100;
  }

  ImagesToAddHiddenField.value = ImageId;

  if (document.getElementById('ctl00_here_HiddenAddImagesToLightBoxTriggerButton'))
  {
    __doPostBack('ctl00$here$HiddenAddImagesToLightBoxTriggerButton', '');
  }
}

function HandleDownloadImageByImageId(pImageId)
{
  var selectedImagesArray = pImageId.split(',')
  
  if (selectedImagesArray && (selectedImagesArray.length == 1))
  {
    newWindow('DownloadMultipleImages.aspx?images=' + pImageId, 'Download', 501, 701, ',location=no,toolbar=no,directories=no,status=no,scrollbars=yes,menubar=no');
    return;
  }
  
  var oneColumnWidth = 156;
  var gapWidth = 165;
  var sideGap = 29;
  var numberOfColumns = parseInt((screen.width - gapWidth - sideGap) / oneColumnWidth);
  var uselessSpace = (screen.width - gapWidth - sideGap)  % oneColumnWidth;
  var gapWidthReal = gapWidth + uselessSpace;
  var gapHeight = 270;
  var clientWidth = screen.width - gapWidthReal;
  
  var w = window.open(uncache('DownloadMultipleImages.aspx?images=' + pImageId + '&numberOfColumns=' + numberOfColumns),'AapDownloadMultipleImages', GetPopupWindowParameters(gapWidthReal, gapHeight));
  w.focus();
}

function HandleDownloadImage(pCheckBoxId)
{
  var CheckBoxPassed = $get(pCheckBoxId);
  
  if (CheckBoxPassed)
  {
    SetAapCheckBoxChecked(CheckBoxPassed, true);
  }

  var selectedImageId = GetSelectedImages('');

  HandleDownloadImageByImageId(selectedImageId);
}

//Open Lightbox popup from search page after adding Images
function OpenLightBoxAfterMultipleImageAdd()
{
  var CurrentLightBox;
  var overlay = document.getElementById('overlay');
  var resultContainer = document.getElementById('searchResults');
   
  $get('ctl00_here_hfSelectedImages').value = '';
  
  if (document.getElementById('ctl00_here_CurrentLightBoxAlbumID'))
  {
    document.getElementById('ctl00_UcSide_lightbox_CurrentLightBoxAlbumID').value = document.getElementById('ctl00_here_CurrentLightBoxAlbumID').value
  }
  
  if (document.getElementById('ctl00_UcSide_lightbox_CurrentLightBoxAlbumID'))
  { 
    CurrentLightBox = document.getElementById('ctl00_UcSide_lightbox_CurrentLightBoxAlbumID').value
  }
  
  var lightBoxWindowParameters = GetPopupWindowParameters(100, 270);
  window.open(uncache('LightBox.aspx?AlbumID=' + CurrentLightBox),'LightBox', lightBoxWindowParameters);
  
  if (overlay && resultContainer)
  {
    overlay.style.display = 'none';
    resultContainer.style.paddingTop = '0px';
  }
}

function ShowHideCalendar(sender, direction)
{
  if (sender == null)
    return;
  
  var datePicker = null;
  
  datePicker = $find(sender);  
  
  if (datePicker == null)
    return;

  var textBox = datePicker.get_textBox();
  var popupElement = datePicker.get_popupContainer();
  
  var dimensions = datePicker.getElementDimensions(popupElement);
  var position = datePicker.getElementPosition(textBox);
  
  if (datePicker.isPopupVisible())
  { 
    datePicker.hidePopup(); 
  }
  else
  { 
    if (direction == "Up")
    {
      datePicker.showPopup(position.x, position.y - dimensions.height - 4); 
    }
    else if (direction == "Bottom")
    {
      datePicker.showPopup(position.x, position.y + textBox.clientHeight + 4); 
    }
  }
}

function ValidateDatePicker(sender, args)
{
  var isDateValid = true;
  var datePicker = $find(sender.controltovalidate);
  var textBox = datePicker.get_textBox();

  if (args.Value == "" && textBox.value != "")
  { 
    isDateValid = false; 
  }
  
  args.IsValid = isDateValid;
}

function ValidateDateTimePicker(sender, args)
{
  var isDateTimeValid = true;
  var dateTimePicker = $find(sender.controltovalidate);
  var textBox = dateTimePicker.get_textBox();

  if (args.Value == "" && textBox.value != "")
  { 
    isDateTimeValid = false; 
  }
  
  args.IsValid = isDateTimeValid;
}

// This function is called when we need to check/uncheck a bunch of checkboxes through javascript.
// Used on search page to select/unselect images to add them to lightbox
// Also used on lightbox page to remove images from lightbox
function OnSelectUnselectAllClicked(parentControl, CheckBoxClicked)
{
  var allPnlGridTextViewCheckBoxes = $get(parentControl).getElementsByTagName("INPUT");
 
  for (i = 0; i < allPnlGridTextViewCheckBoxes.length; i++) 
  {
    var e = allPnlGridTextViewCheckBoxes[i];
    
	  if (e.type == "checkbox" && e.id != CheckBoxClicked.id) 
	  {
	    SetAapCheckBoxChecked(e, CheckBoxClicked.checked);
	  }
  }
};

function OpenAdvancedSearchWindow()
{
  newWindow('AdvancedSearch.aspx', 'AdvancedSearch', '581', '580', ',scrollbars=yes,resizable=yes');
};
