
function addTooltip(objTooltip, varPosition) {
  var bolHidden = false;
  
  arrHiddenTooltips.each( function(item) {
    if(item == objTooltip.id) bolHidden = true;
  });
  
  if(!bolHidden) new Overlay().show(objTooltip, { position : varPosition, opacity : 1, duration: 10000 });
}


function hideTooltip(e, objTooltip) {
  Overlay.hide(e);
  new Ajax.Request("include/ajax_prefset.asp?k=HideTooltip&v=" + objTooltip.id, {method: 'get'});
}


function ShopPaymentDetailsInit() {
	//attach handlers
	//brauch ich erstmal nicht mehr
//	$('UserFirstname').observe('keyup', ShopPaymentFillElvAccountHolder);
//	$('UserLastname').observe('keyup', ShopPaymentFillElvAccountHolder);
//	$('UserCompany').observe('keyup', ShopPaymentFillElvAccountHolder);

	//intit the payment selection
	if($('payment-accordion')) accordion = new Accordion("payment-accordion", "accordion-toggle-trigger", .5, false);
	
}

//function ShopPaymentFillElvAccountHolder() {
//	if($F('UserCompany') != '') {
//		var strString = $F('UserCompany');
//	} else {
//		var strString = $F('UserFirstname') + ' ' + $F('UserLastname');
//	}
//	
//	$('OrderPaymentElvAccountHolder').value = strString.replace(/ {2,}/g,' ').trim();
//}


function ShopUserDetailsInit() {
  //attach handler th the country input to switch the country state field on or off for vertain countries
  $('UserCountry').observe('change', ShopUserDetailsHandleState);
  ShopUserDetailsHandleState()

  //show or hide the ust id input
  if($('UserUstId')) {
    if($('UserUstId').value != "") {
      $('UserUstIdBlockOn').show();
      $('UserUstIdBlockOff').hide();
    } else {
      $('UserUstIdBlockOn').hide();
      $('UserUstIdBlockOff').show();
    }
  }

  if($('PayoutBusinessType0')) {
    if($('PayoutBusinessType0').checked) {
      $('PayoutBusinessBlockOn').hide();
      $('PayoutBusinessBlockOff').show();
    } else {
      $('PayoutBusinessBlockOn').show();
      $('PayoutBusinessBlockOff').hide();
    }
  }

  //show or hide the address extension input
  if($('UserAddress2').value != "") {
    $('UserAddress2BlockOn').show();
    $('UserAddress2BlockOff').hide();
  } else {
    $('UserAddress2BlockOn').hide();
    $('UserAddress2BlockOff').show();
  }
}


function FormHandlePassword() {
  //get all password input fields and attach a handler to keep the password field input on hitting the back button after a form submit
  $$('input[type="password"]').each(function(el) {
    if($(el.name+'Store')) {
      $(el.name).observe('change', FormHandlePasswordEvent);
      if($(el.name+'Store').value != "") el.value = $(el.name+'Store').value;
    }
  });
}

function FormHandlePasswordEvent(e) {
  var el = e.element();
  $(el.name+'Store').value = el.value;
}


function ShopUserDetailsHandleState() {
  var el = $('UserCountry');

  if(el.value == "US" || el.value == "CA") {
    $('UserCountryState').show();
    $('UserCountryStateLabel').show();
  } else {
    $('UserCountryState').hide();
    $('UserCountryStateLabel').hide();
  }
}


//function togles between two images names [imageName].[extension] and [imageName]_active.[extension] to do a mouse over effect
function toggleOverImage(theElement, bolInitialStatusActive) {
  if(!bolInitialStatusActive) {
    if(theElement.src.indexOf('_active.') > 0) {
      theElement.src = theElement.src.substring(0, theElement.src.indexOf('_active.')) + theElement.src.substring(theElement.src.length - 4, theElement.src.length);
    } else {
      theElement.src = theElement.src.substring(0, theElement.src.lastIndexOf('.')) + '_active' + theElement.src.substring(theElement.src.length - 4, theElement.src.length);
    }
  }
}



function activateTab(strTabActive, strTabGroup, bInit){
  //hide all tabs of the tab group
  var arrTabGroup = strTabGroup.split(', ');

  for (var i=0; i<arrTabGroup.length; i+=1) {
    document.getElementById('tabbox_' + arrTabGroup[i]).style.display = "none";
    document.getElementById('tab_' + arrTabGroup[i]).className = "";
  }

  //show active tab
  document.getElementById('tabbox_' + strTabActive).style.display = "block";
  document.getElementById('tab_' + strTabActive).className = "active";

  var bHistory = SWFAddress.getHistory();

  if(!bInit){
	  SWFAddress.setHistory(false);
	  SWFAddress.setValue('/' + strTabActive + '/');
	  SWFAddress.setHistory(bHistory);
	};

  return false;
}


function handleChangePhotoDetail(event) {
	var path = (event.path == "/") ? sTabListActiveTab : event.path.substr(1, event.path.length-2);
	if(path != "extsearch") activateTab(path, 'similarphotos, similartopics, comments', true);
}


function setFocusToField(strField){
  if(document.getElementById(strField)) document.getElementById(strField).focus();
}

function kmSmRemoveSelectedPhotos() {
  //count selected photos
  var intPhotosSelected = 0

  $$('.PhotoFormCheckbox').each(function(item) {
      if (item.checked) {
        intPhotosSelected += 1;
      }
  });

  if (intPhotosSelected == 0) {
    alert("No photos selected.");

  }	else if (confirm("Remove " + intPhotosSelected + " photo(s) from search result?")) {
		document.getElementById('PhotoForm').action = 'keywordmanager.asp?m=photoremovekeyworddo&search=' + getQueryVariable('search') + '&p=' + getQueryVariable('p');
    document.getElementById('PhotoForm').submit();
	}

}

function custDlcUpdate(elmt, strCurrency, dblRate) {
  if (!document.getElementById) return;

  //we round everything to full euro always. just looks better.

  var intCredit = parseInt(elmt.value);

  if (isNaN(intCredit) || intCredit < 100 || intCredit > 1000) {
    document.getElementById('custDlcPrice').innerHTML = '-';
    document.getElementById('custDlcDiscount').innerHTML = '-';

  }else{
    var intLowCredit = 100;
    var intLowDiscount = 10;

    var intHighCredit = 1000;
    var intHighDiscount = 20;

    //calculate anb round discount
    var dblRel = (intHighDiscount - intLowDiscount) / (intHighCredit - intLowCredit);
    var dblDiscount = dblRel * intCredit + intHighDiscount - dblRel * intHighCredit;
    dblDiscount = Math.round(dblDiscount);


    //caculate discount amount and final price
    var dblPriceDiscount = (dblDiscount / 100) * intCredit;
    var dblPrice = (intCredit - dblPriceDiscount);


    //exchange currency if not euro
    if(strCurrency == 'Dollar') {
      dblPrice = dblPrice * dblRate;
      dblPriceDiscount = dblPriceDiscount * dblRate;
    }

    //round final price and discount
    dblPrice = Math.round(dblPrice);
    dblPriceDiscount = Math.round(dblPriceDiscount);


    //format currency
    dblPrice = new String(dblPrice);
    dblPriceDiscount = new String(dblPriceDiscount);
    dblDiscount = new String(dblDiscount);

    if(dblPrice.indexOf('.') < 0) { dblPrice += '.00'; }
    if(dblPrice.indexOf('.') == (dblPrice.length - 2)) { dblPrice += '0'; }

    if(dblPriceDiscount.indexOf('.') < 0) { dblPriceDiscount += '.00'; }
    if(dblPriceDiscount.indexOf('.') == (dblPriceDiscount.length - 2)) { dblPriceDiscount += '0'; }

    if(strCurrency == 'Euro') {
      dblPrice.replace('.', ',');
      dblPriceDiscount.replace('.', ',');

      dblPrice = dblPrice + ' ' + '€';
      dblPriceDiscount = dblPriceDiscount + ' ' + '€';
      dblDiscount = dblPriceDiscount + ' (' + dblDiscount + '%)';

    } else if(strCurrency == 'Dollar') {
      dblPrice = dblPrice + ' ' + '$';
      dblPriceDiscount = dblPriceDiscount + ' ' + '$';
      dblDiscount = dblPriceDiscount + ' (' + dblDiscount + '%)';

    } else {
      //unsupported currency
      dblPrice = '-';
      dblDiscount = '-';
    }

    document.getElementById('custDlcPrice').innerHTML = dblPrice;
    document.getElementById('custDlcDiscount').innerHTML = dblDiscount;
  }
}


function licSelect(elmt) {
  if (!document.getElementById) return;

	elmt.getElementsByTagName('input')[0].checked = true;

	$$('.PhotoLicenceSizeSelect').each(function(item) {
    if (item.getElementsByTagName('input')[0].checked) {
      item.className = 'PhotoLicenceSizeSelect PhotoLicenceSizeSelectActive';
    }else{
      item.className = 'PhotoLicenceSizeSelect';
    }
  });
}

function extLicSelect(elmt) {
  if (!document.getElementById) return;

  if (elmt.checked) {
    elmt.parentNode.className = 'extendedLicence extendedLicenceActive';
  }else{
    elmt.parentNode.className = 'extendedLicence';
  }
}

function licSelectionInit(strInitialPriceType) {
  if (!document.getElementById) return;

  $$('.PhotoLicenceSizeSelect').each(function(item) {
    if (item.getElementsByTagName('input')[0].checked) {
      item.className = 'PhotoLicenceSizeSelect PhotoLicenceSizeSelectActive';
    }else{
      item.className = 'PhotoLicenceSizeSelect';
    }
  });

  $$('.extendedLicence').each(function(item) {
    if (item.childNodes[1].checked) {
      item.className = 'extendedLicence extendedLicenceActive';
      ToggleBlock('ExtendedLicence');
      document.getElementById('ExtendedLicenceOn').style.display = "block";
      document.getElementById('ExtendedLicenceOff').style.display = "none";
    }else{
      item.className = 'extendedLicence';
    }
  });

  if(strInitialPriceType != 'credit') licSelectionSwitchPrice(strInitialPriceType, false);

}


function licSelectionSwitchPrice(strType, bolSaveSetting) {
  if (!document.getElementById) return;

  if(strType == "single") {
    $$('.PriceInfoCredit').each(function(item) {
      item.style.display = "none";
    });

    $$('.PriceInfoSingle').each(function(item) {
      item.style.display = "block";
    });

    $('PhotoLicenceForm').action = $('SinglePurchaseUrl').action;    
    

  } else {
    $$('.PriceInfoSingle').each(function(item) {
      item.style.display = "none";
    });

    $$('.PriceInfoCredit').each(function(item) {
      item.style.display = "block";
    });

    $('PhotoLicenceForm').action = 'photodownload.asp?m=addtocart';

  };

//erstmal ausgemacht. war vom gefühl her komisch. ausserdem soll der focus auf dem credit kauf liegen
//  if(bolSaveSetting) {
//  	new Ajax.Request("include/ajax_prefset.asp?k=UserLicSelectionPriceType&v=" + strType, {method: 'get'});
//  };

}




function downloadCartInit(oForm, sIdList) {
  if (!oForm) return;

  downloadCartCancelSave = false;

  //attach event handlers
  oForm.observe('click', function() { downloadCartHandleChange(sIdList, oForm); });
  oForm.observe('change', function() { downloadCartHandleChange(sIdList, oForm); });
  oForm.observe('submit', function() { downloadCartCancelSave = true; $('DownloadCartHideOnSubmit').hide(); $('DownloadCartShowOnSubmit').show(); });


  //attach event to save the form when the user leaves the page
  Event.observe(window, 'beforeunload', function() { downloadCartSave(oForm); });

  sDownloadCartSetting = oForm.serialize();

  //call it once to update all prices
  downloadCartHandleChange(sIdList, oForm);
}


//function saves the download cart on the server
function downloadCartSave(oForm) {
  if (downloadCartCancelSave != true && sDownloadCartSetting != oForm.serialize()) {
    //submit the download cart form to the ajax handler to save it
  	var sAction = oForm.action;
    oForm.action = 'include/ajax_savedownloadcart.asp';

    oForm.request();

    oForm.action = sAction;
  }
}


//function updates prices when the user changes the downlaod cart
function downloadCartHandleChange(sIdList, oForm) {
  var iDownloadTotal, iDownloadPayedTotal, iTotal, iPayedTotal, iSinglePurchaseTotal

  iDownloadTotal = 0;       //number of credits needed for a photo in the cart
  iDownloadPayedTotal = 0;  //number of payed credits -"-
  iTotal = 0;               //number of credits needed for all photos in the cart
  iPayedTotal = 0;          //number of payed credits -"-
  iSinglePurchaseTotal = 0; //money needed for buying the photo by single purchase order

  sIdList.split(', ').each( function(id) {
    iDownloadTotal = aPhotoLicenceSizeCost[$F('Download'+id+'LicenceSize') -1];
    
    //if this is a upgrade remove the number of credits that got payed already
    if(Object.isNumber(window['iDownload'+ id + 'UpgradeCreditPayedBase'])) {
      iDownloadTotal = iDownloadTotal - window['iDownload'+ id + 'UpgradeCreditPayedBase'];
      if(iDownloadTotal < 0) iDownloadTotal = 0;
    }
    
    
    iDownloadPayedTotal = 0;

    if($('Download'+id+'ExtendedLicenceNoCredit')) {
      if($F('Download'+id+'ExtendedLicenceNoCredit')) iDownloadPayedTotal = iDownloadPayedTotal + iPhotoExtendedLicenceNoCreditCost;
      //if($F('Download'+id+'ExtendedLicenceMultiSeat')) iDownloadPayedTotal = iDownloadPayedTotal + iPhotoExtendedLicenceMultiSeatCost;
      if($F('Download'+id+'ExtendedLicenceBigRun')) iDownloadPayedTotal = iDownloadPayedTotal + iPhotoExtendedLicenceBigRunCost;
      if($F('Download'+id+'ExtendedLicenceResale')) iDownloadPayedTotal = iDownloadPayedTotal + iPhotoExtendedLicenceResaleCost;
      
      
      //if this is a upgrade remove the number of credits that got payed already
      if(Object.isNumber(window['iDownload'+ id + 'UpgradeCreditPayedExtended'])) {
        iDownloadPayedTotal = iDownloadPayedTotal - window['iDownload'+ id + 'UpgradeCreditPayedExtended'];
        if(iDownloadPayedTotal < 0) iDownloadPayedTotal = 0;
      }
      
      iDownloadTotal = iDownloadTotal + iDownloadPayedTotal;
    }
        

    //update single download details and price
    if($('SinglePurchaseTotal')) {
      $('PhotoLicenceSize').value = $F('Download'+id+'LicenceSize');
      iSinglePurchaseTotal = aSinglePhotoLicenceSizeCost[$F('Download'+id+'LicenceSize') -1];

      if($('Download'+id+'ExtendedLicenceNoCredit')) {
        if($F('Download'+id+'ExtendedLicenceNoCredit')) {
          $('PhotoExtendedLicenceNoCredit').value = 1;
          iSinglePurchaseTotal = iSinglePurchaseTotal + iSinglePhotoExtendedLicenceNoCreditCost;
        } else {
          $('PhotoExtendedLicenceNoCredit').value = 0;
        }

  //      if($F('Download'+id+'ExtendedLicenceMultiSeat')) {
  //        $('PhotoExtendedLicenceMultiSeat').value = 1;
  //        iSinglePurchaseTotal = iSinglePurchaseTotal + iSinglePhotoExtendedLicenceMultiSeatCost;
  //      } else {
  //        $('PhotoExtendedLicenceMultiSeat').value = 0;
  //      }

        if($F('Download'+id+'ExtendedLicenceBigRun')) {
          $('PhotoExtendedLicenceBigRun').value = 1;
          iSinglePurchaseTotal = iSinglePurchaseTotal + iSinglePhotoExtendedLicenceBigRunCost;
        } else {
          $('PhotoExtendedLicenceBigRun').value = 0;
        }

        if($F('Download'+id+'ExtendedLicenceResale')) {
          $('PhotoExtendedLicenceResale').value = 1;
          iSinglePurchaseTotal = iSinglePurchaseTotal + iSinglePhotoExtendedLicenceResaleCost;
        } else {
          $('PhotoExtendedLicenceResale').value = 0;
        }
      }

      $('SinglePurchaseTotal').update(CurrencyFormat(iSinglePurchaseTotal / 100, sCurrency, iLanguageID));

    }

    $('Download'+id+'CreditCost').update(iDownloadTotal + ' Credits');

    iTotal = iTotal + iDownloadTotal;
    iPayedTotal = iPayedTotal + iDownloadPayedTotal;
  });

  $('TotalDownloadCreditCost').update(iTotal + ' Credits');


  if (iCreditsAvailable < iTotal || iPayedCreditsAvailable < iPayedTotal) {
    $('StartDownloadNotEnoughCredits').show();

    $('MyCreditsNotEnough').show();
    
    if($('MyCreditsNotEnough2')) {
      if(iPayedCreditsAvailable < iPayedTotal) {
        $('MyCreditsNotEnough2').hide();
        $('MyCreditsNotEnoughPaid').show();
      } else {
        $('MyCreditsNotEnough2').show();
        $('MyCreditsNotEnoughPaid').hide();
      }
    }

    $('StartDownload').hide();
    $('MyCredits').hide();

    //show the breadcrumb steps
    $$('.breadCrumbNoEnoughCredits').each(function(item) {
      item.show();
    });


    //select a downlaod credit package thats big enough for downloading all the selected photos
    var iMax = $$('.DownloadCreditPackage').size()

    $$('.DownloadCreditPackage').each(function(item, index) {
      if(parseInt(item.id.gsub(/\D/, '')) >= iTotal || index + 1 == iMax) {
        dlcSelect(item);
        throw $break;
      }
    });

  } else {
    $('StartDownloadNotEnoughCredits').hide();
    $('MyCreditsNotEnough').hide();
    
    if($('MyCreditsNotEnough2')) {
      $('MyCreditsNotEnough2').hide();
      $('MyCreditsNotEnoughPaid').hide();
    }

    $('StartDownload').show();
    $('MyCredits').show();

    //hide breadcrumb steps
    $$('.breadCrumbNoEnoughCredits').each(function(item) {
      item.hide();
    });

  };

}




function CurrencyFormat(dAmount, sCurrency, iLanguageID) {
  var sCurrencySymbol = sCurrency;
  if (sCurrency == 'Euro') sCurrencySymbol = "€";
  if (sCurrency == 'Dollar') sCurrencySymbol = "$";

  if(iLanguageID == 2) {
    return number_to_currency(dAmount, {unit : sCurrencySymbol, unitPos : 'trailing', separator : ',', delimiter : '.'});
  } else {
    return number_to_currency(dAmount);
  }
}




function number_to_currency(number, options) {
  try {
    var options   = options || {};
    var precision = options["precision"] || 2;
    var unit      = options["unit"] || "$";
    var unitPos   = options["unitPos"] || "leading";
    var separator = precision > 0 ? options["separator"] || "." : "";
    var delimiter = options["delimiter"] || ",";

    varUnitTrailing = '';
    varUnitLeading = '';
    if(unitPos == 'leading') varUnitLeading = unit;
    if(unitPos == 'trailing') varUnitTrailing = ' ' + unit;

    var parts = parseFloat(number).toFixed(precision).split('.');
    return varUnitLeading + number_with_delimiter(parts[0], delimiter) + separator + parts[1].toString() + varUnitTrailing;
  } catch(e) {
    return number
  }
}

function number_with_delimiter(number, delimiter, separator) {
  try {
    var delimiter = delimiter || ",";
    var separator = separator || ".";

    var parts = number.toString().split('.');
    parts[0] = parts[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1" + delimiter);
    return parts.join(separator);
  } catch(e) {
    return number
  }
}





function CounrySelectionInit(objList) {
  if (!document.getElementById) return;

	objList = document.getElementById(objList)
  objList.onchange = function(){CountrySelectionOnClick(this.options[this.selectedIndex]);}
  objList.onkeypress = function(){CountrySelectionOnClick(this.options[this.selectedIndex]);}

  for (var i = 0; i < objList.options.length; i++) {
    if (objList.options[i].selected) {
      objList.options[i].parentNode.style.backgroundImage = objList.options[i].style.backgroundImage;
    }
  }
}

function CountrySelectionOnClick(e){
  e.parentNode.setAttribute('style', e.getAttribute('style'));
  e.parentNode.style.backgroundRepeat = 'no-repeat';
  e.parentNode.style.backgroundPosition = '4px 50%';
  e.parentNode.style.padding = '4px 4px 4px 24px';
}


function LanguageSelectionInit(objList) {
  if (!document.getElementById) return;
  if (!document.getElementById(objList)) return;

  objList = document.getElementById(objList)
  objList.onchange = function(){LanguageSelectionOnClick(this.options[this.selectedIndex]);}
  objList.onkeypress = function(){LanguageSelectionOnClick(this.options[this.selectedIndex]);}

  for (var i = 0; i < objList.options.length; i++) {
    if (objList.options[i].selected) {
      objList.options[i].parentNode.style.backgroundImage = objList.options[i].style.backgroundImage;
    }
  }
}

function LanguageSelectionOnClick(e){
  e.parentNode.setAttribute('style', e.parentNode.getAttribute('style') + e.getAttribute('style'));
  e.parentNode.style.backgroundRepeat = 'no-repeat';
  e.parentNode.style.backgroundPosition = '4px 60%';
  e.parentNode.style.padding = '0 0 0 20px';
  if (e.text == '') e.parentNode.style.backgroundImage = 'none';
}


function htmlspecialchars(text){
  if(typeof(text)=='undefined'||!text.toString){
    return'';
  }
  if(text===false){
    return'0';
  }else if(text===true){
    return'1';
  }
  return text.toString().replace(/&/g,'&amp;').replace(/"/g,'&quot;').replace(/'/g,'&#039;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}


//fills the contest count down box
function ContestGetCount(theDate, theCountbox) {
  if (!document.getElementById(theCountbox)) return;

	var dateNow = new Date(); //grab current date
	var dateFuture = new Date(theDate); //"Month Day, Year Hour:Minute:Second"
	var amount = dateFuture.getTime() - dateNow.getTime(); //calc milliseconds between dates
	delete dateNow;

	// time is already past
	if(amount < 0){
		document.getElementById(theCountbox).innerHTML="Finish";
	}
	// date is still good
	else{
		days=0;hours=0;mins=0;secs=0;out="";

		amount = Math.floor(amount/1000); //kill the "milliseconds" so just secs

		days=Math.floor(amount/86400);
		amount=amount%86400;

		hours=Math.floor(amount/3600);
		amount=amount%3600;

		mins=Math.floor(amount/60);
		amount=amount%60;

		secs=Math.floor(amount);

//		if(days != 0){out += days +" day"+((days!=1)?"s":"")+", ";}
//		if(days != 0 || hours != 0){out += hours +" hour"+((hours!=1)?"s":"")+", ";}
//		if(days != 0 || hours != 0 || mins != 0){out += mins +" minute"+((mins!=1)?"s":"")+", ";}
//		out += secs +" seconds";

    days = days.toString();
		if (days.length == 1) days = '0' + days

		hours = hours.toString();
		if (hours.length == 1) hours = '0' + hours

		mins = mins.toString();
		if (mins.length == 1) mins = '0' + mins

		secs = secs.toString();
		if (secs.length == 1) secs = '0' + secs

		out = days + ":" + hours + ":" + mins + ":" + secs

		document.getElementById(theCountbox).innerHTML = out;

		setTimeout("ContestGetCount('" + theDate + "', '" + theCountbox + "')", 1000);
	}
}


function ShowSimilarPhotos() {
  var theForm = document.FormSearchByKeywordselection;

  for (i=0,n=theForm.elements.length;i<n;i++) {
    if (theForm.elements[i].name.indexOf('Keyword_') == 0) theForm.elements[i].checked = true;
  }

  theForm.ShowAllSimilar.value = 'True';
  theForm.submit();
}


//returns a random alphanumeric password of specified length
function randomPassword(length)
{
  chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
  pass = "";
  for(x=0;x<length;x++)
  {
    i = Math.floor(Math.random() * 62);
    pass += chars.charAt(i);
  }
  return pass;
}


//returns querystring value by name
function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  }
}


function getQueryVariableFromUrl(sUrl, variable) {
	if(sUrl.indexOf("?") == -1) return;
  var query = sUrl.substr(sUrl.indexOf("?")+1);

  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {

    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  }
}


//returns a random 8 digit alphanumeric string
function GetRandomString() {
  var intLength = 8;
  var strCharList = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"
  var strRandom = "";


  for (i=1; i<=intLength; i++) {
    strRandom = strRandom + strCharList.substr(Math.round(Math.random() * strCharList.length +1), 1);
  }

  return strRandom;
}


function SetFormActionAndSubmit(theForm, theAction) {
  theForm.action = theAction;
  theForm.submit();
}

function ChatStartTimer() {
  setTimeout("ChatCheckRefresh()",5000)
}

function ChatCheckRefresh() {
  if(document.ChatForm.Message.value == '') {
   document.location.href = document.location.href;
  }
  setTimeout("ChatCheckRefresh()",5000)
}


//opens the uplaod status window
function ShowUploadStatus(intUploadID) {
  window.open('progressbar.asp?ID=' + intUploadID, 'win' + intUploadID, 'width=500,height=140');
  return true;
}


//preview a image file selected via file selection form element. works in ie only.
function PreviewImg(el) {
	var filename = el.value;
	var Img = new Image();

	Img.src = filename;
	Img.onload = function() {
	  if(this.width >= this.height) {
  	  this.height *= 164 / this.width;
  	  this.width = 164;
  	}else{
  	  this.width *= 164 / this.height;
  	  this.height = 164;
    }

  	document.PhotoPreview.src = this.src;
  	document.PhotoPreview.height = this.height;
  	document.PhotoPreview.width = this.width;
	}

  Img = null;
}


//replaces the html standard file uplaod with a custom one
function myFileUpload(strImagePath) {
	if (!(document.createElement && document.getElementsByTagName)) return;

	//inspired by http://www.quirksmode.org/dom/inputfile.html

	var fakeFileUpload = document.createElement('div');
	fakeFileUpload.className = 'inputFileFake';

	var fakeFileUploadInput = fakeFileUpload.appendChild(document.createElement('input'));
	fakeFileUploadInput.className = 'inputFile';

	var image = document.createElement('img');
	image.src= strImagePath + 'btn_selectphoto.gif';
	fakeFileUpload.appendChild(image);

	var x = document.getElementsByTagName('input');
	for (var i=0;i<x.length;i++) {
		if (x[i].type != 'file') continue;
		if (x[i].getAttribute('noscript')) continue;
		if (x[i].parentNode.className != 'myFileinput') continue;
		x[i].className = 'inputFileHidden';
		x[i].style.filter = 'alpha(opacity=0.01)'; //added for ie8
		var clone = fakeFileUpload.cloneNode(true);
		x[i].parentNode.appendChild(clone);
		x[i].relatedElement = clone.getElementsByTagName('input')[0];
	}
}


function ShowUploadPreview() {
  var ie = (navigator.userAgent.indexOf('MSIE') > -1) ? 1 : 0;

  if(ie) {
    var myElem = document.getElementById("UploadPreview");
    myElem.style.display = 'block'

    var myElem = document.getElementById("UploadPreviewForm");
    myElem.className = 'boxSubcolumnRight'
  }
}


function AjaxUpdateImageThumb2(strThumbPath, strImageElementID)
{
  new Ajax.Request(strThumbPath,
		{
			method: 'get',
			onSuccess: function(transport)
			{
			  //alert('Found ' + strThumbPath);
			  //	set the thumbnail
  			var e = document.getElementById(strImageElementID);
  			e.src = strThumbPath;

			  return true;
			},
			onFailure: function(transport)
			{
				//alert('Not found ' + strThumbPath);
				setTimeout("AjaxUpdateImageThumb2('" + strThumbPath + "', '" +  strImageElementID + "')", 3000);
				return true;
			}
		});
}

function OpenSmilies(strURL) {
  winExifViewer = window.open(strURL, 'winSmiles', 'location=yes,status=yes,toolbar=yes,menubar=yes,scrollbars=yes,width=400,height=350');
  winExifViewer.focus();
}

function OpenLightbox(strURL) {
  winLightbox = window.open(strURL, 'winLightbox', 'location=yes,resizable=yes,status=yes,toolbar=yes,menubar=yes,scrollbars=yes,width=640,height=530');
  winLightbox.focus();
}

function OpenChat(strURL, strWindowname) {
  winChat = window.open(strURL, strWindowname, 'location=yes,resizable=yes,status=yes,toolbar=yes,menubar=yes,scrollbars=yes,width=640,height=530');
  winChat.focus();
}

function OpenHelp(strURL) {
  winHelp = window.open(strURL, 'winHelp', 'location=no,resizable=yes,status=yes,toolbar=no,menubar=no,scrollbars=yes,width=640,height=660');
  winHelp.focus();
}

function OpenerLink(strURL) {
  if(parent.opener){
    parent.opener.location.href = strURL;
    parent.opener.focus();
  }else{
    location.href = strURL;
  }
}


//lightbox stuff


// neue checkbox funktionen. die können dann mal in den lightbox scripten ausgetauscht werden
function setCheckboxGroup(strFormID, strGroupPrefix, bolChecked) {
  var theForm = document.getElementById(strFormID);

  for (i=0,n=theForm.elements.length;i<n;i++) {
    if (theForm.elements[i].name.indexOf(strGroupPrefix) == 0) theForm.elements[i].checked = bolChecked;
  }
}

function invertCheckboxGroup(strFormID, strGroupPrefix) {
  var theForm = document.getElementById(strFormID);

  for (i=0,n=theForm.elements.length;i<n;i++) {
    if (theForm.elements[i].name.indexOf(strGroupPrefix) == 0) {
      if (theForm.elements[i].checked == false) {
        theForm.elements[i].checked = true;
      } else {
        theForm.elements[i].checked = false;
      }
    }
  }
}



function SelectAllPhotos() {
  var theForm = document.FormLightboxPhotos;

  for (i=0,n=theForm.elements.length;i<n;i++) {
    if (theForm.elements[i].name.indexOf('chk') == 0) theForm.elements[i].checked = true;
  }
}

function DeSelectAllPhotos() {
  var theForm = document.FormLightboxPhotos;

  for (i=0,n=theForm.elements.length;i<n;i++) {
    if (theForm.elements[i].name.indexOf('chk') == 0) theForm.elements[i].checked = false;
  }
}

function ReversePhotoSelection() {
  var theForm = document.FormLightboxPhotos;

  for (i=0,n=theForm.elements.length;i<n;i++) {
    if (theForm.elements[i].name.indexOf('chk') == 0) {
      if (theForm.elements[i].checked == false) {
        theForm.elements[i].checked = true;
      } else {
        theForm.elements[i].checked = false;
      }
    }
  }
}

function CountSelectedPhotos() {
		var theForm = document.FormLightboxPhotos;
		var selectedPhotos = 0;

		for (i=0,n=theForm.elements.length;i<n;i++) {
      if (theForm.elements[i].name.indexOf('chk') == 0 && theForm.elements[i].checked == true) selectedPhotos++;
    }

		return selectedPhotos;
}

function GetSelectedPhotoIDs() {
  var theForm = document.FormLightboxPhotos;
  var strPhotoIDs = "";

  for (i=0,n=theForm.elements.length;i<n;i++) {
  	if (theForm.elements[i].name.indexOf('chk') == 0 && theForm.elements[i].checked == true) strPhotoIDs += theForm.elements[i].value + ", ";
  }

  if (strPhotoIDs != "") {
     strPhotoIDs = String(strPhotoIDs).substring(0,String(strPhotoIDs).length-2);
  }

  return strPhotoIDs;
}

function DownloadSelectedPhotos(strFormAction) {
  var theForm = document.FormLightboxPhotos;
  var intPhotoCount = CountSelectedPhotos();

  if (intPhotoCount > 0) {
    theForm.SelectedPhotoIDs.value = GetSelectedPhotoIDs();
    theForm.target = window.opener.name;
    theForm.action = strFormAction;
    theForm.submit();
    
    window.opener.focus();
  }
}

function RemoveSelectedPhotos(strFormAction) {
  var theForm = document.FormLightboxPhotos;
  var intPhotoCount = CountSelectedPhotos();

  if (intPhotoCount > 0) {
    theForm.SelectedPhotoIDs.value = GetSelectedPhotoIDs();
    theForm.action = strFormAction;
    theForm.submit();
  }
}

function CopySelectedPhotos(strFormAction) {
  var theForm = document.FormLightboxPhotos;
  var intPhotoCount = CountSelectedPhotos();

  if (intPhotoCount > 0) {
    theForm.SelectedPhotoIDs.value = GetSelectedPhotoIDs();
    theForm.action = strFormAction;
    theForm.submit();
  }
}

function MoveSelectedPhotos(strFormAction) {
  var theForm = document.FormLightboxPhotos;
  var intPhotoCount = CountSelectedPhotos();

  if (intPhotoCount > 0) {
    theForm.SelectedPhotoIDs.value = GetSelectedPhotoIDs();
    theForm.action = strFormAction;
    theForm.submit();
  }
}


function NotificationRemoveSelected(strFormAction) {
  var theForm = document.FormNotification;

  theForm.action = strFormAction;
  theForm.submit();
}

function NotificationMoveSelected(strFormAction) {
  var theForm = document.FormNotification;

  theForm.action = strFormAction;
  theForm.submit();
}

function NotificationMarkSelectedAsRead(strFormAction) {
  var theForm = document.FormNotification;

  theForm.action = strFormAction;
  theForm.submit();
}

function NotificationToggle(theForm) {
  for (i=0,n=theForm.elements.length;i<n;i++) {
    if (theForm.elements[i].name.indexOf('chk') == 0) {
      theForm.elements[i].checked = theForm.ToggleNotifications.checked
    }
  }
}


function trim(str) {
  //return str.replace(/^\s*|\s*$/g,"");
  return String(str).replace(/^\s*|\s*$/g,"");
}

function isEmpty(s) {
	return ((s == null) || (s.length == 0));
}


//displays a status on the security of a given keyword
function checkPasswordSecurity(target) {
	var TestWords = false;
	var TestNumberOfChars = false;
	var TestUppercaseChars = false;
	var TestLowercaseChars = false;
	var TestDigits = false;
	var TestSpecialChars = false;
	var TestCounter = false;
	var TestWhiteSpaces = false;
	var TestSecondPassword = false;

	var counter = 0;
	strInput = target.value;
	objImage = document.images.PasswordSecurity


	/* Check if length of password is greather then 8 */

	if(strInput.length >= 8) {

		if(!TestNumberOfChars) {		// do it only if the counter is 8, if it's greather, the TestNumberOfChars will be true and the right image is shown

			TestNumberOfChars = true;

		}
	} else {

		TestNumberOfChars = false;

	}


	/* check uppercase Letters */

	if(strInput.match(/[A-Z]/)) {

		TestUppercaseChars = true;

	} else {

		TestUppercaseChars = false;

	}

	/* check lowercase letters */

	if(strInput.match(/[a-z]/)) {

		TestLowercaseChars = true;

	} else {

		TestLowercaseChars = false;

	}


	/* check for digits */

	if(strInput.match(/[0-9]/)) {

		TestDigits = true;

	} else {

		TestDigits = false;

	}


	/* check special chars */

	if(strInput.match(/[^a-zA-Z0-9]/)) {

		TestSpecialChars = true;

	} else {

		TestSpecialChars = false;

	}


	/* Check for whitespaces and ESC-Sequences */

	if(strInput.match(/\s/)) {

		TestWhiteSpaces = true;

	} else {

		TestWhiteSpaces = false;

	}


	if(TestUppercaseChars) { counter++; }
	if(TestLowercaseChars) { counter++; }
	if(TestDigits)         { counter++; }
	if(TestSpecialChars)   { counter++; }
	if(TestWhiteSpaces)   { counter++; }
	if(TestNumberOfChars)   { counter++; }

	if(counter == 0) { objImage.src = "images/pwdsec0.gif"; }
  if(counter == 1) { objImage.src = "images/pwdsec1.gif"; }
  if(counter == 2) { objImage.src = "images/pwdsec2.gif"; }
  if(counter == 3) { objImage.src = "images/pwdsec3.gif"; }
  if(counter == 4) { objImage.src = "images/pwdsec4.gif"; }
  if(counter == 5) { objImage.src = "images/pwdsec5.gif"; }
  if(counter == 6) { objImage.src = "images/pwdsec6.gif"; }

}

function ToggleBlock(obj) {
  if (document.getElementById(obj + 'On').style.display == "none" || document.getElementById(obj + 'On').style.display == "")
  {
  	document.getElementById(obj + 'On').style.display = "block";
    document.getElementById(obj + 'Off').style.display = "none";
  }
  else
  {
    document.getElementById(obj + 'On').style.display = "none";
    document.getElementById(obj + 'Off').style.display = "block";
  }
}

function InputSet(obj, text) {
  document.getElementById(obj).value = text
}



/* popup windows */
function NewWindow(mypage, myname, w, h, scroll) {
  winprops = 'height='+h+',width='+w+',scrollbars='+scroll+',resizable=no, top=20, left=20'
  win = window.open(mypage, myname, winprops)
  if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
}

 var Behaviour = {
    register: function(rules){
      this.rules = rules;
      for(rule in this.rules){
        this.reload(rule);
      }
    },

    reload: function(rule){
      elements = $$(rule);
      for(y=0;y<elements.length;y++){
        this.rules[rule](elements[y]);
      }
    }

  }



pcBehaviour = {
  'a.popFaq':function(elmt) {
    elmt.onclick = function() {
      NewWindow(this.href, 'winHelp', '640', '660', 'yes');
      return false;
    }
  },

  'form':function(elmt) {
    var elmtOnSubmit = elmt.onsubmit;
    
    elmt.onsubmit = function() {
      //disable all input buttons
      $$('input[type="image"]').each(function(item) {
        item.disabled = true;
      });
      
      if (elmtOnSubmit != null) {
        elmtOnSubmit();
      } else {
        return true;
      }
    }
  }


};




//function inits the extended search
function extSearchInit() {
  if (document.getElementById('extendedSearch')) {
    Behaviour.register(photosearchrules);
    SWFAddress.addEventListener(SWFAddressEvent.CHANGE, handleChangeExtSearch);

    if (document.getElementById('color1').value != '') document.getElementById('color_select_icon1').style.background = document.getElementById('color1').value;

    if (document.getElementById('catselectId').value != '')  {
      if(_cs == null) var _cs = new CatSelector();
      _cs.setSelection(document.getElementById('catselectId').value);
    }
  }
}


//function resets all extened search values
function extSearchReset() {
  //document.getElementById('SearchPhotoInput').value = document.getElementById('SearchPhotoInput').title;
  //document.getElementById('SearchPhotoInputExt').value = document.getElementById('SearchPhotoInputExt').title;

  document.getElementById('SearchPhotoID').value = "";
  document.getElementById('SearchPhotoFilename').value = "";
  document.getElementById('SearchPhotoUserName').value = "";

  document.getElementById('SearchPhotoFormatSquare').checked = true;
  document.getElementById('SearchPhotoFormatPortrait').checked = true;
  document.getElementById('SearchPhotoFormatLandscape').checked = true;
  document.getElementById('SearchPhotoFormatPanorama').checked = true;

  document.getElementById('SearchPhotoWidth').value = document.getElementById('SearchPhotoWidth').title;
  document.getElementById('SearchPhotoHeight').value = document.getElementById('SearchPhotoHeight').title;
  document.getElementById('SearchPhotoResUnit').selectedIndex = 0;

  $$('.dpi').each(function(item) {
    item.style.color = '#CDCED0';
    $(item.htmlFor).checked = false;
    $(item.htmlFor).disabled = true;
  });

  document.getElementById('SearchPhotoColormodeColor').checked = false;
  document.getElementById('SearchPhotoColormodeBlackAndWhite').checked = false;

  document.getElementById('SearchPhotoExtendedLicence').checked = false;

  if(document.getElementById('catselectId').value != ""){
    document.getElementById('catselectId').value = "";
    _cs.setSelection("");
  }

  cs1_delete_color();

}


//function handles the swfaddress change event
var bExtShown;


// ich musste den zuklapp effekt rausnehmen. da gab es probleme in allen browsern. manchmal klappte dann die suche überhaupt nicht auf oder zu. ich hab nicht rausbekommen woran es lag
function handleChangeExtSearch(event) {
	if (event.path == "/extsearch/") {
	  if(!bExtShown) {
	    document.getElementById('extendedSearch').style.display = 'block';
	  } else {
	    Effect.PhaseIn('extendedSearch');
	  }
	} else {
	  document.getElementById('extendedSearch').style.display = 'none';
	};

	bExtShown = true;
}



//function handleChangeExtSearch(event) {
//	if (event.path == "/extsearch/") {
//	  if(!bExtShown) {
//	    //Effect.PhaseIn('extendedSearch');
//	    $('extendedSearch').style.display = 'block';
//	  } else {
//	    //Effect.PhaseIn('extendedSearch');
//	    //$('extendedSearch').style.display = 'block';
//
//	    //$('extendedSearch').style.display == 'none';
//	    //if($('extendedSearch').style.display == 'none') Effect.PhaseIn('extendedSearch');
//
//	    //var temp = new Effect.PhaseIn('extendedSearch', { beforeStart: function() { alert($('extendedSearch').style.display) }, afterFinish: function() { alert($('extendedSearch').style.display) } } );
//	    /*alert("PhaseIn");
//	    Effect.PhaseIn('extendedSearch');
//	    document.title= $('extendedSearch').getStyle('display');*/
//	    //alert("232");
//	    document.title= $('extendedSearch').getStyle('display') + 'adsad';
//	    $('extendedSearch').style.display = 'block';
//	  }
//	} else {
//	  //Effect.PhaseOut('extendedSearch');
//	  //$('extendedSearch').style.display = 'none';
//
//    //alert($('extendedSearch').style.display);
//    //document.getElementById('extendedSearch').style.display == 'block';
//	  //if($('extendedSearch').style.display == 'block') Effect.PhaseOut('extendedSearch');
//
//	  document.title= $('extendedSearch').getStyle('display');
//	  Effect.PhaseOut('extendedSearch');
//	};
//
//	bExtShown = true;
//}



photosearchrules = {
  'a.toggleExtSearch':function(elmt) {
    elmt.onclick = function() {
      //set a new swfaddress to call the swfaddress change event and open or close the extended search

      var bHistory = SWFAddress.getHistory();
      SWFAddress.setHistory(false);

      if (SWFAddress.getPath() != "/extsearch/") {
    	  SWFAddress.setValue('/extsearch/');
    	} else {
        SWFAddress.setValue('/');
    	}

    	SWFAddress.setHistory(bHistory);
    	return false;
    }
  },

  'input.SetSearchFieldTitle':function(elmt) {
      elmt.onfocus = function() {
      if(this.value == this.title) this.value = '';
  	},
  	elmt.onblur = function() {
      if(this.value == '') this.value = this.title;
  	}
  },

  '#SearchPhotoInput':function(elmt) {
      elmt.onchange = function() {
      if(this.value == '') this.value = this.title;
      document.getElementById('SearchPhotoInputExt').value = this.value;
  	}
  },

  '#SearchPhotoInputExt':function(elmt) {
      elmt.onchange = function() {
      if(this.value == '') this.value = this.title;
      document.getElementById('SearchPhotoInput').value = this.value;
  	}
  },

  'select.PhotoResUnit':function(elmt) {
      elmt.onchange = function() {
          var px = this.value=='px';
          $$('.dpi').each(function(item) {
              item.style.color = px ? '#CDCED0' : '#645D5B';
              $(item.htmlFor).disabled = px;
          });
          var px = this.value=='px';
           $$('.dpi').each(function(item) {
              item.style.color = px ? '#CDCED0' : '#645D5B';
              var cb = $(item.htmlFor);
              cb.disabled = px;
              if (px)
              cb.checked = !px;
          });

  	}
  }
};





var VisibleHeight = -1;
var InitialPos = 0;

function initScrolling(elementId) {
	var e = document.getElementById(elementId);
	var pos = getPosition(e);

	InitialPos = pos.y;
}

function getPosition(element) {
  var elem=element,tagname="",x=0,y=0;

  while ((typeof(elem)=="object")&&(typeof(elem.tagName)!="undefined"))
  {
    y+=elem.offsetTop;
    x+=elem.offsetLeft;
    tagname=elem.tagName.toUpperCase();

    if (tagname=="BODY")
      elem=0;

    if (typeof(elem)=="object")
      if (typeof(elem.offsetParent)=="object")
        elem=elem.offsetParent;
  }

  position=new Object();
  position.x=x;
  position.y=y;
  return position;
}

function getVisibleHeight()
{
	return document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
}

function moveComments(elementId)
{
	//check if the community tab is opened
	if($('tabbox_comments').style.display == 'none') {
		VisibleHeight = -1;
		return;
	};

	//init scrolling if this is the first use
	if(VisibleHeight == -1) {
		VisibleHeight = 0;
		InitialPos = 0;

		initScrolling(elementId);
	};

	var Element = document.getElementById(elementId);
	var height = getVisibleHeight();

	if(height - InitialPos <= 0)
		height = 0;
	else height = (height - InitialPos);

	Element.style.marginTop = height+"px";

	return true;
}









function dlcSelect(elmt) {
  if (!document.getElementById) return;

  if(elmt.tagName == 'INPUT') {
    //the checkbox has been clicked
    elmt.checked = "checked";

  }else{
    //the table has been clicked
    elmt.getElementsByTagName('input')[0].checked = true;
  }


	$$('.shopDlcSelectPacket').each(function(item) {
    if (item.getElementsByTagName('input')[0].checked) {
      item.className = 'shopDlcSelectPacket shopDlcSelectPacketActive';
      if(item.getElementsByTagName('input')[1]) if(item.getElementsByTagName('input')[1].value <= "1") item.getElementsByTagName('input')[1].value = 1;
    }else{
      item.className = 'shopDlcSelectPacket';
      if(item.getElementsByTagName('input')[1]) item.getElementsByTagName('input')[1].value = 0;
    }
  });
}


function dlcSelectInit() {
  if (!document.getElementById) return;

  $$('.shopDlcSelectPacket').each(function(item) {
    if (item.getElementsByTagName('input')[0].checked) {
      item.className = 'shopDlcSelectPacket shopDlcSelectPacketActive';
      if(item.getElementsByTagName('input')[1]) item.getElementsByTagName('input')[1].value = 1;
    }else{
      item.className = 'shopDlcSelectPacket';
      if(item.getElementsByTagName('input')[1]) item.getElementsByTagName('input')[1].value = 0;
    }

  });

}