/**
* This file contains general javascript functions
*/

function OpenNewWindow( aUrl )
     {
     url = new String( aUrl );
     /*
     // Add schema if missing
     if ( 'http://' != url.substr( 0, 7 ) )
          {
          url = 'http://' + url;
          }
     */
     winid=window.open( url );
     winid.focus();
     }

/**
* Sets the price of the publication
*/
function SetPrice( aPiece, aFormatPrices, aFormatId, aPriceElement  )
    {
    var price = document.getElementById( aPriceElement );
    // Accept only numbers as a piece
    if ( aPiece > 0 || aPiece == '' )
        {
        aPiece = Math.round( aPiece );
        price.innerHTML = aPiece * aFormatPrices[aFormatId] + ' Ft';
        }
    else
        {
        aPiece.value = 1;
        price.innerHTML = aPrice + ' Ft';
        }
    }

/**
* Sets the price of the publication
*/
function SetIssuePrice( aPrice, aPriceElement  )
    {
    var price = document.getElementById( aPriceElement );
    price.innerHTML = aPrice + ' Ft.';
    }


/**
*
*/
function ShowDiv( id, aDisplay )
     {
     var display = 'block';
     if ( aDisplay )
        {
        display = 'inline';
        }

     // safe function to show an element with a specified id
     if (document.getElementById)
          { // DOM3 = IE5, NS6
          document.getElementById(id).style.display = display;
          }
     else
          {
          if (document.layers)
               { // Netscape 4
               document.id.display = display;
               }
          else
               { // IE 4
               document.all.id.style.display = display;
               }
          }
     }

/**
*
*/
function HideDiv( id )
     {
     //safe function to hide an element with a specified id
     if (document.getElementById)
          { // DOM3 = IE5, NS6
          document.getElementById(id).style.display = 'none';
          }
     else
          {
          if (document.layers)
               { // Netscape 4
               document.id.display = 'none';
               }
          else
               { // IE 4
               document.all.id.style.display = 'none';
               }
          }
     }

/**
*
*/
function SetSubscribePriceField( aCheckBox, aDivId, aDisplay, aField )
    {
    if ( aCheckBox.checked )
        {
        ShowDiv( aDivId, aDisplay );
        }
    else
        {
        var field = document.getElementById( aField );
        if ( field )
            {
            field.value = '';
            }

        HideDiv( aDivId );
        }
    }

/**
*
*/
function ShowIssueLength( aFormatIds, aShowFormatId )
    {
    for ( index in aFormatIds )
        {
        document.getElementById( 'LengthOfFormatId'+index ).style.display = 'none';
        }
    document.getElementById( 'LengthOfFormatId'+aShowFormatId ).style.display = 'block';
    }

/**
*
*/
function SetSubscribeLengthPrice( aFormatId, aPriceTag )
    {
    var lengthList = document.getElementById( 'LengthOfFormatId'+aFormatId );
    var price = lengthList.options[lengthList.selectedIndex].value;
    temps = price.split( '_' );
    document.getElementById( aPriceTag ).innerHTML = temps[1]+' Ft';
    }

/**
*
*/
function decrypt_str( aStr, aKey )
    {
    var to_dec = aStr;
    var result = "";
        var xor_key = aKey;
        for( i = 0; i < to_dec.length; i++ )
            {
                result += String.fromCharCode( xor_key ^ to_dec.charCodeAt( i ) );
            }
        return result;
    }

/**
*
*/
function encrypt(str, pwd) {
  if(pwd == null || pwd.length <= 0) {
    alert("Please enter a password with which to encrypt the message.");
    return null;
  }
  var prand = "";
  for(var i=0; i<pwd.length; i++) {
    prand += pwd.charCodeAt(i).toString();
  }
  var sPos = Math.floor(prand.length / 5);
  var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos*2) + prand.charAt(sPos*3) + prand.charAt(sPos*4) + prand.charAt(sPos*5));
  var incr = Math.ceil(pwd.length / 2);
  var modu = Math.pow(2, 31) - 1;
  if(mult < 2) {
    alert("Algorithm cannot find a suitable hash. Please choose a different password. \nPossible considerations are to choose a more complex or longer password.");
    return null;
  }
  var salt = Math.round(Math.random() * 1000000000) % 100000000;
  prand += salt;
  while(prand.length > 10) {
    prand = (parseInt(prand.substring(0, 10)) + parseInt(prand.substring(10, prand.length))).toString();
  }
  prand = (mult * prand + incr) % modu;
  var enc_chr = "";
  var enc_str = "";
  for(var i=0; i<str.length; i++) {
    enc_chr = parseInt(str.charCodeAt(i) ^ Math.floor((prand / modu) * 255));
    if(enc_chr < 16) {
      enc_str += "0" + enc_chr.toString(16);
    } else enc_str += enc_chr.toString(16);
    prand = (mult * prand + incr) % modu;
  }
  salt = salt.toString(16);
  while(salt.length < 8)salt = "0" + salt;
  enc_str += salt;
  return enc_str;
}

/**
*
*/
function decrypt(str, pwd) {
  if(str == null || str.length < 8) {
    alert("A salt value could not be extracted from the encrypted message because it's length is too short. The message cannot be decrypted.");
    return;
  }
  if(pwd == null || pwd.length <= 0) {
    alert("Please enter a password with which to decrypt the message.");
    return;
  }
  var prand = "";
  for(var i=0; i<pwd.length; i++) {
    prand += pwd.charCodeAt(i).toString();
  }
  var sPos = Math.floor(prand.length / 5);
  var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos*2) + prand.charAt(sPos*3) + prand.charAt(sPos*4) + prand.charAt(sPos*5));
  var incr = Math.round(pwd.length / 2);
  var modu = Math.pow(2, 31) - 1;
  var salt = parseInt(str.substring(str.length - 8, str.length), 16);
  str = str.substring(0, str.length - 8);
  prand += salt;
  while(prand.length > 10) {
    prand = (parseInt(prand.substring(0, 10)) + parseInt(prand.substring(10, prand.length))).toString();
  }
  prand = (mult * prand + incr) % modu;
  var enc_chr = "";
  var enc_str = "";
  for(var i=0; i<str.length; i+=2) {
    enc_chr = parseInt(parseInt(str.substring(i, i+2), 16) ^ Math.floor((prand / modu) * 255));
    enc_str += String.fromCharCode(enc_chr);
    prand = (mult * prand + incr) % modu;
  }
  return enc_str;
}

/**
*
*/
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

function encode64(input) {
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   do {
      chr1 = input.charCodeAt(i++);
      chr2 = input.charCodeAt(i++);
      chr3 = input.charCodeAt(i++);

      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;

      if (isNaN(chr2)) {
         enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
         enc4 = 64;
      }

      output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) +
         keyStr.charAt(enc3) + keyStr.charAt(enc4);
   } while (i < input.length);

   return output;
}

/**
* decode64
*/
function s(input) {
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
   input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

   do {
      enc1 = keyStr.indexOf(input.charAt(i++));
      enc2 = keyStr.indexOf(input.charAt(i++));
      enc3 = keyStr.indexOf(input.charAt(i++));
      enc4 = keyStr.indexOf(input.charAt(i++));

      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;

      output = output + String.fromCharCode(chr1);

      if (enc3 != 64) {
         output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
         output = output + String.fromCharCode(chr3);
      }
   } while (i < input.length);

   return output;
}

/**
*
*/
function CharCounter( aInputField, aMaxLength, counterElementId )
    {
    var str = aInputField.value;
    var length = aInputField.value.length;

    if ( length > aMaxLength )
        {
        str = str.substring( 0, aMaxLength );
        aInputField.value = str;
        }

    counter = document.getElementById( counterElementId );
    var size = aMaxLength - length;
    if ( size < 0 ) size = 0;
    counter.innerHTML = size;
    }

/**
*
*/
function PopupWindow( aWidth, aHeight, aUrl )
     {
     var w = aWidth; // window width
     var h = aHeight; // window height
     // Position window to screen center.
     var t=window.screen.height/2-(h/2); // window`s top position
     var l=window.screen.width/2-(w/2); // window`s left position
     // Open window.
     winid=window.open(aUrl,'guide','scrollbars=no,top='+t+',left='+l+',width='+w+',height='+h+'');
     winid.focus();
     }

/**
*
*/
function PopupFullScreenWindow( aUrl )
     {
     // Open window.
     winid=window.open( aUrl,'fs','scrollbars=auto,fullscreen=yes');
     winid.focus();
     }

/**
*
*/
function CollapsPanel( aPanelId, aControlId, aAnimateToLength )
    {
    var myAnim = new YAHOO.util.Anim( aPanelId );
    myAnim.duration = 0.5;
    myAnim.method = YAHOO.util.Easing.easeOut;

    if ( document.getElementById( aPanelId ).style.height != '0px' )
        {
        myAnim.attributes.height = { to: 0 };
        document.getElementById( aControlId ).innerHTML = '&gt;&gt;';
        }
    else
        {
        myAnim.attributes.height = { to: aAnimateToLength };
        document.getElementById( aControlId ).innerHTML = '&lt;&lt;';
        }

    myAnim.animate();
    }

/**
*
*/
function isNumberKey( aEvent )
    {
    var charCode = ( aEvent.which ) ? aEvent.which : aEvent.keyCode
    if ( charCode > 31 && ( charCode < 48 || charCode > 57 ) )
        {
        return false;
        }
    return true;
    }

/**
* Sets the visibility of the price ui when the publisher adds a new issue, and selects "elofizetheto lapok" from the "kiadvany formatuma" drop down list.
* If the "elofizetheto lapok" cannot be selected because the publisher did not defined subscribtion length before, so he cannot add an "elofizethetolapok" type of issue,
*  aDisablePrice is true.
* @param aSelectFieldId Value of the selected list iitem of the "kiadvany formatuma" drop down list.
* @param aDisablePrice If true, the prise ui wont be visible despite that the selected item is "elofizetheto lapok", and an alert will be shown, with an error message.
*/
function SetPriceUiVisibility( aPriceUiId, aSelectUiId, aSelectUiErrorId, aDisablePrice )
    {
    if ( document.getElementById( aSelectUiId ).value == 1 )
        {
        if ( !aDisablePrice )
            {
            document.getElementById( aSelectUiErrorId ).innerHTML = '';
            document.getElementById( aPriceUiId ).style.display = 'block';
            }
        else
            {
            document.getElementById( aSelectUiId ).value = 0;
            document.getElementById( aSelectUiErrorId ).innerHTML = 'Előfizethető kiadvány hozzáadása előtt meg kell adnia az előfizetési időtartamokat!';
            }
        }
    else
        {
        document.getElementById( aSelectUiErrorId ).innerHTML = '';
        document.getElementById( aPriceUiId ).style.display = 'none';
        }
    }

/**
*
*/
function ValidateIssueData( aTitleUiId, aTitleUiErrorId, aDescriptionShortUiId,
                           aDescriptionShortUiErrorId, aDescriptionUiId, aDescriptionUiErrorId )
    {
    error = false;
    if ( document.getElementById( aTitleUiId ).value == '' )
        {
        document.getElementById( aTitleUiErrorId ).innerHTML = 'Nem adta meg a kiadvány nevét!';
        error = true;
        }
    else
        {
        document.getElementById( aTitleUiErrorId ).innerHTML = '';
        }

    if ( document.getElementById( aDescriptionShortUiId ).value == '' )
        {
        document.getElementById( aDescriptionShortUiErrorId ).innerHTML = 'Nem adta meg a kiadvány rövid leírását!';
        error = true;
        }
    else
        {
        document.getElementById( aDescriptionShortUiErrorId ).innerHTML = '';
        }

    if ( document.getElementById( aDescriptionUiId ).value == '' )
        {
        document.getElementById( aDescriptionUiErrorId ).innerHTML = 'Nem adta meg a kiadvány leírását!';
        error = true;
        }
    else
        {
        document.getElementById( aDescriptionUiErrorId ).innerHTML = '';
        }
    return !error;
    }

/**
*
*/
function ValidatePublicationData( aPublicationUiId, aPublicationUiErrorId )
    {
    error = false;
    if ( document.getElementById( aPublicationUiId ).value == '' )
        {
        document.getElementById( aPublicationUiErrorId ).innerHTML = 'Nem adta meg a példány nevét!';
        error = true;
        }
    else
        {
        document.getElementById( aPublicationUiErrorId ).innerHTML = '';
        }
    return !error;
    }

function findPos(obj) 
    {
        var curleft = curtop = 0;
        if (obj.offsetParent) {
                curleft = obj.offsetLeft
                curtop = obj.offsetTop
                while (obj = obj.offsetParent ) {
                        curleft += obj.offsetLeft
                        curtop += obj.offsetTop
                }
        }
        return [curleft,curtop];
    }
    
/**
*
*/
function ShowArrowAndScroll( aPontToId, aArrowImageName )
    {
    // Find position of element
    pointTo = findPos( document.getElementById ( aPontToId ) );
    
    // Create arrow image
    newimg = document.createElement('img');
    newimg.src = aArrowImageName;
    newimg.style.display = 'block';
    newimg.style.position = 'absolute';
    newimg.style.zorder = '1';
    newimg.style.left = ( pointTo[0] - newimg.width ) + 'px';
    newimg.style.top = ( pointTo[1] - ( newimg.height / 2) ) + 'px';
    document.getElementsByTagName( "body" ).item( 0 ).appendChild( newimg );
    
    //Scroll to bottom of page
    window.scrollBy( 0, document.body.scrollHeight );
    }
    
var handleYes = function() 
    {
    this.hide();
    
    window.location = this.iNextUrl;
    }

var handleCancel = function() 
    {
    this.hide();
    }

var handleOk = function() 
    {
    this.hide();
    }
    
function MessageBox( aTitle, aMsgText, aDialogType, aNextUrl )
    {
    var myButtons;
    
    if ( aDialogType == 0 ) // dialog type: yescancel
        {
        var myButtons = [ { text:"Igen", handler:handleYes },
                          { text:"Mégsem", handler:handleCancel } ];        
        }
    if ( aDialogType == 1 ) // dialog type: ok
        {
        var myButtons = [ { text:"Ok", handler:handleOk } ];        
        }    

    mySimpleDialog = new YAHOO.widget.SimpleDialog( "dlg", {
        width: "20em",
        fixedcenter:true,
        modal:true,
        close:false,
        draggable:false });
    mySimpleDialog.setHeader( aTitle );
    mySimpleDialog.setBody( aMsgText );
    mySimpleDialog.cfg.queueProperty("buttons", myButtons);
    mySimpleDialog.render(document.body);
    mySimpleDialog.show();
    mySimpleDialog.iNextUrl = aNextUrl        
    }
    
function BankAccountFieldControl( aKeyEvent, aValue, aNextFieldId )
    {
    var keyNum;

    // Check browser and extract keynumber
    if ( window.event ) // IE
        {
        keyNum = aKeyEvent.keyCode;
        }
    else if( aKeyEvent.which ) // Netscape/Firefox/Opera
        {
        keyNum = aKeyEvent.which;
        }

    var keyChar = String.fromCharCode( keyNum );
    var numKeyRegEx = /\D/;
    var specKeyRegEx = /[\x00\x08\x0D]/;

    if ( numKeyRegEx.test( keyChar ) && !specKeyRegEx.test( keyChar) )
        {
        // Not a nuber and not a special char
        return false;
        }
    else
        {
        if ( aValue.length == 8 && aNextFieldId != '' && !specKeyRegEx.test( keyChar ) )
            {
            // Input field is filled, jump to the next field
            document.getElementById( aNextFieldId ).focus();
            document.getElementById( aNextFieldId ).value = keyChar;
            return false;
            }
        // Its a number
        return true;
        }
    } 
    
/**
*
*/    
function IsEmailFormatValid( aEmailAddress ) 
    {
    if ( aEmailAddress.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1 )
        {
        return true;
        }
    else
        {
        return false;
        }
    }  
