// Handle all the the FSCommand messages in a Flash movie
function setLanguage(args)
{
   document.location = '/setlanguage.php?lang=' + args + '&referer=' + escape(document.location.href);
}

var Utils =
{
  getRandomId: function(prefix)
  {
    var id = 0;
    do
    {
      id = Math.round(Math.random()*10000);
    }
    while(typeof($(prefix + id)) != 'undefined' && $(prefix + id) != null);
    return id;
  },
  handleError: function(transport, json)
  {
    var str = 'An error occured: ';

    if(json)
    {
      str += json.message;
    }
    else
    {
      if(transport.status == 200)
        str += 'Unknown error';
      else
        str += transport.statusText;
    }

    alert(str);
  },
  displayFormError: function(container, displayError, validators)
  {
    var str = '<ul>';
    validators.each(function(v){
      str += '<li>' + v.options.message + '</li>';
    });
    str += '</ul>';
    new AlertBox(str, {alertType: 'Warning', okButtonClass: 'button'});
  },
  createCookie: function(name,value,days)
  {
    if(days)
    {
      var date = new Date();
      date.setTime(date.getTime()+(days*24*60*60*1000));
      var expires = "; expires="+date.toGMTString();
    }
    else
      var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
  },
  readCookie: function(name)
  {
  	var nameEQ = name + "=";
  	var ca = document.cookie.split(';');
  	for(var i=0;i < ca.length;i++)
  	{
  		var c = ca[i];
  		while (c.charAt(0)==' ') c = c.substring(1,c.length);
  		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  	}
  	return null;
  },
  eraseCookie: function(name)
  {
    createCookie(name,"",-1);
  },
  /* ************************************************************
  Created: 20060120
  Author:  Steve Moitozo <god at zilla dot us> -- geekwisdom.com
  Description: This is a quick and dirty password quality meter
  		 written in JavaScript so that the password does
  		 not pass over the network.
  License: MIT License (see below)
  Modified: 20060620 - added MIT License
  Modified: 20061111 - corrected regex for letters and numbers
                       Thanks to Zack Smith -- zacksmithdesign.com
  ---------------------------------------------------------------
  Copyright (c) 2006 Steve Moitozo <god at zilla dot us>

  Permission is hereby granted, free of charge, to any person
  obtaining a copy of this software and associated documentation
  files (the "Software"), to deal in the Software without
  restriction, including without limitation the rights to use,
  copy, modify, merge, publish, distribute, sublicense, and/or
  sell copies of the Software, and to permit persons to whom the
  Software is furnished to do so, subject to the following
  conditions:

     The above copyright notice and this permission notice shall
  be included in all copies or substantial portions of the
  Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
  KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
  AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
  OR OTHER DEALINGS IN THE SOFTWARE.
  ---------------------------------------------------------------


  Password Strength Factors and Weightings

  password length:
  level 0 (3 point): less than 4 characters
  level 1 (6 points): between 5 and 7 characters
  level 2 (12 points): between 8 and 15 characters
  level 3 (18 points): 16 or more characters

  letters:
  level 0 (0 points): no letters
  level 1 (5 points): all letters are lower case
  level 2 (7 points): letters are mixed case

  numbers:
  level 0 (0 points): no numbers exist
  level 1 (5 points): one number exists
  level 1 (7 points): 3 or more numbers exists

  special characters:
  level 0 (0 points): no special characters
  level 1 (5 points): one special character exists
  level 2 (10 points): more than one special character exists

  combinatons:
  level 0 (1 points): letters and numbers exist
  level 1 (1 points): mixed case letters
  level 1 (2 points): letters, numbers and special characters
  					exist
  level 1 (2 points): mixed case letters, numbers and special
  					characters exist

  ************************************************************ */
  testPassword: function(passwd)
  {
  		var score = 0;

  		// PASSWORD LENGTH
  		if (passwd.length<5)                         // length 4 or less
  			score += 3;
  		else if (passwd.length>4 && passwd.length<8) // length between 5 and 7
  			score += 6;
  		else if (passwd.length>7 && passwd.length<16)// length between 8 and 15
  			score += 12;
  		else if (passwd.length>15)                    // length 16 or more
  			score += 18;

      var hasLetter = false;
      var haslowerLetter = false;
  		// LETTERS (Not exactly implemented as dictacted above because of my limited understanding of Regex)
  		if (passwd.match(/[a-z]/))                              // [verified] at least one lower case letter
  		{
  			score += 1;
  			hasLowerLetter = true;
  			hasLetter = true;
  		}
      var hasUpperLetter = false;
  		if (passwd.match(/[A-Z]/))                              // [verified] at least one upper case letter
  		{
  			score += 5;
  			hasLetter = true;
  			hasUpperLetter = true;
  		}

  		var hasNumber = false;
  		// NUMBERS
  		if (passwd.match(/\d+/))                                 // [verified] at least one number
  		{
  			score += 5;
  			hasNumber = true;
  		}

  		if (hasNumber && passwd.match(/(.*[0-9].*[0-9].*[0-9])/))             // [verified] at least three numbers
  		{
  			score += 5;
  		}


  		var hasSpecialChar = false;
  		// SPECIAL CHAR
  		if (passwd.match(/.[!,@,#,$,%,^,&,*,?,_,~]/))            // [verified] at least one special character
  		{
  			score += 5;
  			hasSpecialChar = true;
  		}

      // [verified] at least two special characters
  		if (hasSpecialChar && passwd.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/))
  		{
  			score += 5;
  		}


  		// COMBOS
  		if (hasLowerLetter && hasUpperLetter)        // [verified] both upper and lower case
  		{
  			score += 1;
  		}

  		if (hasLetter && hasNumber) // [verified] both letters and numbers
  		{
  			score += 1;
  		}

      // [verified] letters, numbers, and special characters
  		if (hasLetter && hasNumber && hasSpecialChar)
  		{
  			score += 2;
  		}

  		return Math.round((score/48)*100);
  },

  initFileUploads: function(root, size)
  {
      var f = new Element('div', {'class': 'fakefile'});
      f.appendChild(new Element('input', {type: 'text', size: size}));
      f.appendChild(new Element('img', {src: "/globalIcons/ie/AppBasic/16x16/plain/folder_up.png", width: 16, height: 16}));
      $A($(root).getElementsBySelector('div.file')).each(function(e)
      {
          var c = $(f.cloneNode(true));
          e.appendChild(c);
          var i = e.down('input');
          i.relatedElement = c.down('input');
          i.addClassName('hidden');
          Event.observe(i, 'change', function(){ this.relatedElement.value = this.value; });
          Event.observe(i, 'mouseout', function(){ this.relatedElement.value = this.value; });
      });
  }
}

var Popup = {
  show: function(name, file, width, height, params)
  {
    var features = 'scrollbars=yes, width=' + width.toString() + ', height=' + height.toString();
    window.open(file + '?' + params, name, features);
  }
}

Object.extend(Form,
{
  needConfirmation: false,
  confirmationMessage: "**",

  setSelectedValue: function(select, value)
  {
    select = $(select);
    for(var i = 0; i < select.options.length; i++)
    {
      if(select.options[i].value == value)
      {
        select.selectedIndex = i;
        return;
      }
    }
  },
  selectAll: function(checkbox, container, name)
  {
    var fields = $A($(container).getElementsByTagName('input'));
    fields.each(function(field)
    {
      if(field.name == name)
      {
        field.checked = checkbox.checked;
      }
    });
  },
  clearElement: function(element)
  {
    element = $(element);
    if(element.tagName == 'INPUT' || element.tagName == 'TEXTAREA')
      element.value = '';
    else if(element.tagName == 'SELECT')
    {
      for(var i = 0; i < element.options.length; i++)
        element.options[i].selected = false;
    }
  },
  disable: function(element, exceptions)
  {
    exceptions = (exceptions || {});
    element = $(element);
    var els = $A(element.getElementsByTagName('input'));
    els.each(function(el){if(!exceptions[el.id] && !exceptions[el.name]) el.disabled='disabled';});
    els = $A(element.getElementsByTagName('select'));
    els.each(function(el){if(!exceptions[el.id] && !exceptions[el.name]) el.disabled='disabled';});
    els = $A(element.getElementsByTagName('textarea'));
    els.each(function(el){if(!exceptions[el.id] && !exceptions[el.name]) el.disabled='disabled';});
    els = $A(document.getElementsByClassName('formElement', element));
    els.each(function(el){if(!exceptions[el.id] && !exceptions[el.name]) Element.hide(el);});
  },

  confirmExit: function(needConfirmation, message)
  {
    if(this.needConfirmation == needConfirmation)
      return;

    if(needConfirmation)
    {
      if(message)
        this.confirmationMessage = message;
      window.onbeforeunload = this.onBeforeUnload.bind(this);
    }
    else
      window.onbeforeunload = null;
    this.needConfirmation = needConfirmation;
  },

  onBeforeUnload: function()
  {
    return this.confirmationMessage;
  }
});

LoginValidator = Class.create();
LoginValidator.prototype = Object.extend(new Validator(),
{
  initialize: function(element, options)
  {
    this.element = $(element);
    this.setOptions({ currentUser: 0 }, options);
    FormValidate.Validators.register(this);
  },
  isValid: function()
  {
    var v = this.getValue(this.element);
    if(v == null || v.length <= 0)
      return true;

    var req = new Ajax.Request(webRoot + '/_ajax/users.php', {
      method: 'get',
      parameters: 'method=_loginExists&args[0]=' + v + '&args[1]=' + this.options.currentUser,
      asynchronous: false
    });
    req = new Ajax.Response(req);
    var json = req.responseJSON;
    return json.out != true;
  }
});

function closeAlertBox()
{
	$('alertBox_overlay').remove();
	$('alertBox_overlayContent').remove();
}
function openLwAlertRss()
{
	myLightWindow.activateWindow({href: '/stayInTouch/rss.php', title: '', type: 'page', width: 700, height: 500});
}
function openLwAlertMail()
{
	myLightWindow.activateWindow({href: '/stayInTouch/email.php', title: '', type: 'page', width: 700, height: 500});
}
function openLwSponsorShip()
{
    myLightWindow.activateWindow({href: '/sponsorship.php', title: '', type: 'page', width: 700, height: 500});	
    $('alertBox_overlay').remove();
	$('alertBox_container').remove();
}

Event.observe(window, 'keypress', function(e)
{
    if(e.keyCode == 13 && e.target.tagName == 'INPUT' && (e.target.type == 'text' || e.target.type == 'password'))
    {
        var f = $(e.target).up('form');
        if(f && (typeof f.onsubmit == 'undefined' || f.onsubmit()))
        {
            f.submit();
        }
    }
}.bindAsEventListener(window));

var GlobuleCaptcha =
{
  getAnother: function()
  {
    new Ajax.Request("/lw/register.php?captcha=new",
    {
      method: "get",
      onSuccess: this.showAnother.bind(this)
    });
  },
  showAnother: function(transport)
  {
    $('GlobuleCaptcha-img').src = '/lw/register.php?captcha=' + transport.responseText;
    $('code').value = transport.responseText;
  }
}

