/*

Vidoop Secure Client Script - Javascript



This script defines the imgSecurity object that forms the core of the client layer.  imgSecurity communicates with

the web layer, sending it user input and receving its responses as XML data.  imgSecurity also displays and controls

user interface elements such as the image grid.

*/

var MASTER_VIDOOP_WEBROOT;


/*Need to modify this line */

VIDOOP_WEBROOT = "../../aspx/community/";
VIDOOP_IMGROOT = "../../img/imageAuthentication/";




if (undefined!=MASTER_VIDOOP_WEBROOT) {

    VIDOOP_WEBROOT = MASTER_VIDOOP_WEBROOT;

}



AUTHCORE_SCRIPT = "ImageBasedAuth.aspx";
var HANDLER = "";



var image_identifiers  = new Array();

var image_descriptions = new Array();

var image_links        = new Array();

var image_mouseover    = new Array();



//imgSecurity class handles the behaviors of the login grid

function imgSecurity(lang){
    this.dirty          = false;			//This is a flag that prevents the grid from being called a second time on keystrokes
    this.loaded         = Array();			//Array of boolean flags, one for each image in the grid.  Set to true when the image has loaded
    this.ajax           = new imgSecAjax();	//AJAX handler
    this.progress       = 0;                //Percentage of total number of grid images that have finished loading
    this.handler_string = Array();          //Array of handler names that can be passed to the server script
    this.param_string   = Array();          //Array of parameter names that can be passed to the server script
    this.response_tags  = Array();          //Array of names of XML tags that can be received from the server script
    this.grid_config    = new Array();      //Grid config options (background color, dimensions, etc)
    this.locked         = false;            //Flag indicating that a request is in progress so new ones should not be made
    this.image_code_map = "";               //Identifier for an image grid
    this.token_name     = "";               //Name of token to associate with user (this is used as the name of both a cookie and a Flash shared object)
	this.config_ready   = false;			//Flag indicating if the config xml has been loaded
	this.vidsec_remember = false;           //Flag indicating that the user has checked the "this is my computer" box
    this.language       = lang;

	//Draggable Windows
	this.dragObject  	= null;
	this.mouseOffset 	= null;
	this.windowOffset = 13;
	this.windowSnap = 15;
	this.windowTop = 17;
	this.windowLeft = 0;
	try {

			this.startX = cookieVal("vidsec_window_x");
    		this.startY = cookieVal("vidsec_window_y");

	} catch(e){
		this.startX = 0;
		this.startY = 0;
	}
	document.onmousemove = this.mouseMove;
	document.onmouseup = this.mouseUp;

	//Page elements
    this.divContainer = document.getElementById('vidsec_container');
    this.divImages = document.getElementById('vidsec_images');
    this.divLoader = document.getElementById('vidsec_loader');
    //this.vidsec_user = document.getElementById('hdnLoginId');

    this.vidsec_user = getFormField("aspnetForm", _controlPrefix_id + "hdnLoginId");
    //this.vidsec_successURL=getFormField("aspnetForm", _controlPrefix_id + "hdnSuccessURL");  
    //this.vidsec_failureURL= getFormField("aspnetForm", _controlPrefix_id + "hdnFailureURL");  
    this.vidsec_sequence=getFormField("aspnetForm", _controlPrefix_id + "hdnVICS");
    this.vidsec_gridcolor = getFormField("aspnetForm", _controlPrefix_id + "hdnImgGridColor");
    
//    this.vidsec_user_label = document.getElementById('vidsec_user_label');
	this.vidsec_login = getFormField("aspnetForm", _controlPrefix_id + "txtSSN");  
	
/*	try{

	    this.vidsec_card_login = document.getElementById('vidsec_card_login');

	}catch(e){}*/
    this.form = document.getElementById('aspnetForm');

    //Object to read/write swf tokens

    try{
        this.swf_token = new SWFObject(VIDOOP_WEBROOT + "swf/vidsec_token.swf","swf_token","1","1","7","");
        this.swf_token.write("vidsec_swf_token_container");
        this.swf_token = document.getElementById("swf_token");
    }catch(e){
		//console.log('Failed to create swf object:'+e);
	}

   //Get variable names to be used in querystrings for AJAX calls
   
    this.getConfig();

}



//Chooses a handler for the XML received from the server as a result of an AJAX call

imgSecurity.prototype.handleResponse = function(xmlNode){

    if(xmlNode.nodeName == 'xml'){
        xmlNode = xmlNode.nextSibling;
    }
    //The name of the top-level node tells us what needs to be done with the data
    switch(xmlNode.nodeName){
        //Grid List - Use data to build and display the image grid
        case this.response_tags["grid_list"]:
			this.showGrid(xmlNode);
        break;
        //Channel List - Use data to build and display an offband channel selection prompt
        case this.response_tags["channel_list"]:
            this.selectOffbandChannel(xmlNode.firstChild);
        	break;
        //Password Prompt - Display a password prompt
        case this.response_tags["password_prompt"]:
            this.passwordPrompt(false);
        	break;
        //Enroll Prompt - Redirect to the enrollment page
        case this.response_tags["enroll_prompt"]:
            this.gotoEnroll();
        	break;
        //Password Change Prompt - Display a control allowing user to submit a new password
        case this.response_tags["password_change_prompt"]:
            this.changePasswordPrompt();
            break;
        //Login Result - Redirect to appropriate page based on final result of login process
        case this.response_tags['login_result']:
            this.processLoginResult(xmlNode);
        	break;
        //Infocard Username - Take the username from the response and run it through the submitUserID function
        case this.response_tags['infocard_username']:
            this.submitInfocardUserID(xmlNode);
            break;
        //Error - Display error message in an alert div
        case this.response_tags["error"]:
			var msg = getNodeText(xmlNode);
			this.showToolTip('vidsec_error', msg, 402, 'error', null, null, 'imgSec.lock(false)');
			break;
        case this.response_tags["category_reset_code_prompt"]:
	        this.categoryResetCodePrompt(xmlNode);
	        break;

    }

}


imgSecurity.prototype.getConfig = function(){
	var me = this;
    
	this.ajax.onSuccess=function(){
	    //The configXML property holds the entire XML response.  It is not used in this file, but allows extensions to 

	    //access a config response containing a custom config file without having to re-implement the getConfig method.
		me.configXML = this.responseXML;

		// Simulate handleResponse() function because getConfig() is not yet complete.

        
		var xmlNode = this.responseXML.firstChild;
		


		if (xmlNode.nodeName == 'error') {
			me.showToolTip('lblLogonInfo',getNodeText(xmlNode),300,'error');

			return;

		}



		me.request_string = xmlNodeValue("config.request_type",this.responseXML);

        //Assign handler names;

        var hd_arr=this.responseXML.firstChild.getElementsByTagName('handlers')[0].childNodes;

        for(var i=0;i<hd_arr.length;i++){

            me.handler_string[hd_arr[i].nodeName] = xmlNodeValue("config.handlers."+hd_arr[i].nodeName,this.responseXML);

        }

        //Assign parameter names;

        var pm_arr=this.responseXML.firstChild.getElementsByTagName('params')[0].childNodes;

        for(var i=0;i<pm_arr.length;i++){

            me.param_string[pm_arr[i].nodeName] = xmlNodeValue("config.params."+pm_arr[i].nodeName,this.responseXML);

        }

        //Assign response tag names;

        var rt_arr=this.responseXML.firstChild.getElementsByTagName('response_tags')[0].childNodes;

        for(var i=0;i<rt_arr.length;i++){

            me.response_tags[rt_arr[i].nodeName] = xmlNodeValue("config.response_tags."+rt_arr[i].nodeName,this.responseXML);

        }

        //Assign grid config options;

        var gc_arr=this.responseXML.firstChild.getElementsByTagName('grid')[0].childNodes;

        for(var i=0;i<gc_arr.length;i++){

            me.grid_config[gc_arr[i].nodeName] = xmlNodeValue("config.grid."+gc_arr[i].nodeName,this.responseXML);

        }

        me.successURL = xmlNodeValue("config.misc.success_url",this.responseXML);

        me.failureURL = xmlNodeValue("config.misc.failure_url",this.responseXML);

        me.enrollURL  = xmlNodeValue("config.misc.enroll_url",this.responseXML);

        me.homeURL    = xmlNodeValue("config.misc.home_url",this.responseXML); 
        

		me.token_prefix = xmlNodeValue("config.misc.token_prefix",this.responseXML);

		//me.infocard = (xmlNodeValue("config.misc.enable_infocard", this.responseXML) == "true"?true:false);
	    //Prevent any grid fetches from being attempted until config fetch is complete
	    me.config_ready = true;
	    
	    
	    
		if(me.vidsec_login)
    	    me.lock(false);
    	//Set up infocard, if applicable

    	/*if(me.infocard)

    	    me.setupInfocard();*/
    	    
       // me.language = xmlNodeValue("config.language", this.responseXML);

        var langScript = document.createElement('script');

        langScript.type = 'text/javascript';
        
        langScript.src = applicationPath + '/js/imageAuthentication/lang/'+me.language+'/vidsec_grid_text.js';
        
        document.getElementsByTagName("head")[0].appendChild(langScript);
        


	}

	//this.ajax.execute(VIDOOP_WEBROOT + AUTHCORE_SCRIPT + (this.language.length > 0?'?lang='+this.language:''));


	this.ajax.execute(VIDOOP_WEBROOT + AUTHCORE_SCRIPT + (this.language.length > 0?'?lang='+this.language:''));

}



/*Sets up infocard selector button*/

imgSecurity.prototype.setupInfocard = function(){

    if(!document.getElementById('vidsec_infocard_container') || !this.infocard)

        return;

    var me = this;

    this.ajax.onSuccess = function(){

        var card = document.createElement('object');

        card.type = 'application/x-informationcard';

        if(!card.isInstalled)//abort if browser does not have infocard support

            return;

        

        var xml = this.responseXML;

        

        card.tokenType = xmlNodeValue('infocard_config.token_type',xml);

        card.issuer = xmlNodeValue('infocard_config.issuer',xml);

        var list = xml.getElementsByTagName('req_params')[0];

        var tmp = list.childNodes;

        for(var i=0;i<tmp.length;i++){

            card.requiredClaims.add(getNodeText(tmp[i]));

        }



        card.setAttribute('name','vidsec_infoCard');

        card.setAttribute('id','vidsec_infoCard');

        document.getElementById('vidsec_infocard_container').appendChild(card);

        

        if(card.isInstalled){

            document.getElementById('vidsec_infocard_container').style.display="";

            me.infoCard = card;

        }

    }

    this.ajax.execute(VIDOOP_WEBROOT + AUTHCORE_SCRIPT + '?' + this.request_string + '=' + this.handler_string['configure_infocard']);

}



//Get infocard token from user, then submit it to the web layer

imgSecurity.prototype.getInfoCard = function(){

    var card = this.infoCard;

    try{

        var cardVal = card.value;

        cardVal = URLEncode(cardVal);

    }catch(e){

        return false;

    }

    

    var me = this;

    this.ajax.onSuccess = function(){

        me.lock(true);

        me.handleResponse(this.responseXML.firstChild);

        card.value = "";

    }

    

    this.ajax.executePost(VIDOOP_WEBROOT + AUTHCORE_SCRIPT + '?' + this.request_string + '=' + "submit_infocard", "infocard_token=" + cardVal);

}



//Submit user id to web layer script, receive command block for auth mechanism

imgSecurity.prototype.submitUserID=function(){

if(this.locked)
        return false;
    this.lock(true);
    
    //Validatingh the input data
    /*if(!this.vidsec_user.value) 
    {
	    alert("Please enter a Social Security Number.");
		return false;
	} 
	else if(!document.getElementById('vidsec_pin').value) 
	{
	    alert("Please enter a Personal Identification Number.");
		return false;
	}
	else 
	{
	    document.getElementById('safeencpwd').value = safeEncode(document.getElementById('vidsec_pin').value);
	}*/
	
	//var srtValues = '&pin=' + document.getElementById('vidsec_pin').value + '&encryptPassword=' + document.getElementById('safeencpwd').value + '&userType=' + document.getElementById('userType').value + '&siteToken=' + document.getElementById('siteToken').value;
	//alert(VIDOOP_WEBROOT + AUTHCORE_SCRIPT + '?' + this.request_string+'='+this.handler_string['get_token_name']+'&'+this.param_string['user_id']+'='+ this.vidsec_user.value + srtValues);
	//calls the UserTokenNameHandler function in app_code/VidsecHandler.cs (Ajax Request)
    //this.ajax.execute(VIDOOP_WEBROOT + AUTHCORE_SCRIPT + '?' + this.request_string+'='+this.handler_string['get_token_name']+'&'+this.param_string['user_id']+'='+ this.vidsec_user.value + srtValues,false);
    
    //alert(VIDOOP_WEBROOT + AUTHCORE_SCRIPT + '?' + this.request_string+'='+this.handler_string['get_token_name']+'&'+this.param_string['user_id']+'='+ this.vidsec_user.value);
    
    //R12 Changes start
    /*this.ajax.execute(VIDOOP_WEBROOT + AUTHCORE_SCRIPT + '?' + this.request_string+'='+this.handler_string['get_token_name']+'&'+this.param_string['user_id']+'='+ this.vidsec_user.value,false);
    this.token_name = this.token_prefix+xmlNodeValue("token_name",this.ajax.responseXML);*/
    //R12 Changes end
    
     //Get the name of the token we're going to look for
    this.getTokenName();
    
    
    var me=this; 
    this.ajax.onSuccess=function(){
	    //Make sure a valid username has been entered
	   /* if (!me.validateField(me.vidsec_user.value)){
			me.showToolTip('vidsec_error',"Invalid characters in input",250,'error');
			me.lock(false);
		    return;
	    }
	    else if (me.vidsec_user.value.length < 1){
			me.showToolTip('vidsec_error',"Please enter a username",250,'error');
			me.lock(false);
		    return;
	    }*/
        	
        try{ me.fldPass = document.getElementById('vid_pass'); } catch (e) {}
	    try{ me.fldImgCode = document.getElementById('imgcode'); } catch (e) {}
        if(((me.fldPass !== null && me.fldPass.value.length>0) || (me.fldImgCode !== null)) && me.vidsec_user.value.length>0)	{
            me.form.submit();
            return;
        }
        //Determine handler to use response in
        me.handleResponse(this.responseXML.firstChild);
    };
    
     //Check to see if this user has an auth token on this machine, if so then append its value to the request
    var tokenID = this.getToken();
	if(tokenID != null){
		if(tokenID.length>0){
			var tokenStr = '&' +this.param_string['token_id'] + '=' + tokenID;
		} else {
			var tokenStr = '';
		}
	} else {
		var tokenStr = '';
	}
	if (tokenID == '') //when the client cookie does not match the vidoop cookie.
	{
	  var handler = this.handler_string['password_auth'];
	  var url = VIDOOP_WEBROOT + AUTHCORE_SCRIPT + '?' + this.request_string + '=' + handler + 
        '&' + this.param_string['user_id'] + '=' + this.vidsec_user.value + 
        '&' + this.param_string['password'] + '=pass' + 
        '&' + this.param_string['group_sequence'] + '=' + this.vidsec_sequence.value + 
        '&' + this.param_string['token_deposit'] + '=true' +
        '&lang' + '=' + this.language;
        this.ajax.execute(url); // Calls the AuthenticationPasswordAuthenticateHandler function in app_code/VidsecHandler.cs (Ajax Request)
   }
   else
   {
       //Calls the UsernameHandler function in app_code/VidsecHandler.cs (Ajax Request)
        this.ajax.execute(VIDOOP_WEBROOT + AUTHCORE_SCRIPT + '?' + this.request_string+'='+this.handler_string['username']+'&'+this.param_string['user_id']+'='+ this.vidsec_user.value +'&'+ this.param_string['group_sequence']+'='+ this.vidsec_sequence.value + tokenStr + '&lang=' + this.language);
   }

}



//submitAuthGrid sends the image code map and image codes entered by the user

imgSecurity.prototype.submitAuthGrid=function(){    
    
    if(!document.getElementById('auth_code').value || document.getElementById('auth_code').value.indexOf(" ")>-1 )
    {
        alert(ERR_EMPTY_ACCESS_CODE);
        document.getElementById('auth_code').focus();
        return false;
    }
    
    var url=VIDOOP_WEBROOT + AUTHCORE_SCRIPT + "?" + this.request_string + "=" + this.handler_string['grid_auth'];

    url += '&' + this.param_string['user_id'] + '=' + this.vidsec_user.value + 

        '&' + this.param_string['auth_code'] + '=' + document.getElementById('auth_code').value +

        '&' + this.param_string['image_code_map'] + '=' + this.image_code_map +

        '&' + this.param_string['token_id'] + '=' + this.getToken() + 
         
         '&lang=' + this.language;

    var me=this;

    this.ajax.onSuccess = function () {
        me.handleResponse(this.responseXML.firstChild);
    }
    
    this.ajax.execute(url);
    document.getElementById('vidsec_processing').style.visibility = 'visible';

}





// Remove loading screen and make the image grid visible

imgSecurity.prototype.gridMakeVisible = function() {	

    //Turn off the 'Loading...' image and display the grid elements

    
    this.loading(false);

    this.progress=0;

    this.showProgress(this.progress);

    for(var i=0;i<this.grid_config['gridsize'];i++)

    	try{document.getElementById('vidsec_pair'+i).style.visibility = "visible";

        }catch(e){}

	document.getElementById('vidsec_output').style.visibility = "visible";

	document.getElementById('seclogo').style.display = "";

    document.getElementById('vidsec_fields').style.display = "";

    //Set focus on the appropriate input field

    if(!document.getElementById('vid_pass')) {

		document.getElementById('auth_code').focus();

	} else {

		document.getElementById('vid_pass').focus();	

	}

	//Some browsers need to resize the grid slightly

	if (typeof XMLHttpRequest == 'function')

		document.getElementById('vidsec_output').style.width = document.getElementById('vidsec_output').style.width.match(/\d+/) - 4;
		
	//IE hack - forces a re-render so that the stitched image does not get hidden behind the other grid elements

    if(this.grid_config['stitched']=="true" && this.grid_config['popups']=="true")

        document.getElementById("vidsec_stitched_image").style.position="absolute";

}





//loadedImage is called each time a grid image finishes loading.  When the last remaining image has loaded, the grid is made visible

imgSecurity.prototype.loadedImage = function(num){

    //Mark this image as having loaded

    this.loaded[num] = 1;

    //Update progress meter

    this.progress += Math.floor((1/this.grid_config['gridsize']) * 100);

	this.showProgress(this.progress);

    //Check to see if all images are now loaded

    if(this.gridLoaded() ){

		this.gridMakeVisible();

    }

}



//gridLoaded checks to see if any unloaded images remain, if so it returns false

imgSecurity.prototype.gridLoaded = function(){

    if(!inArray(this.loaded,0)){

        return true;

    }

    return false;

}



//Draws the grid

imgSecurity.prototype.showGrid = function(gridList){

    var gridHeight = gridList.getElementsByTagName('grid_height')[0].firstChild.nodeValue;

	var gridWidth = gridList.getElementsByTagName('grid_width')[0].firstChild.nodeValue;

    this.loading(true);

    

    //Determine whether to set token

    try{

        if(getNodeText(gridList.getElementsByTagName('token_id')[0]).length > 0){

            var token_id = getNodeText(gridList.getElementsByTagName('token_id')[0]);

            this.setToken(token_id,'');

        }

    }catch(e){

		//console.log('Failed to set token: '+e);

	}

    

	//output is the HTML that will be drawn

	var output="";

		

	//Start grabbing XML data

	this.image_code_map = xmlNodeValue("image_code_map",gridList);

	var image_list = gridList.getElementsByTagName(this.response_tags['images']);

	image_list = image_list[0].childNodes;

	this.grid_config['gridsize']=image_list.length;

	

	var stitched_image_identifier = xmlNodeValue("stitched_image", gridList);

		

	//Get each image and mark it as not being loaded

	for(var i=0;i<image_list.length;i++){

	    var image = image_list[i];

	    var imgID = xmlNodeValue("image_identifier",image);

	    var desc  = xmlNodeValue("image_description",image);

	    var lnk   = xmlNodeValue("image_link",image);

	    image_identifiers[i]=imgID;

	    image_descriptions[i]=(desc.length>0?desc:"");

	    image_links[i]=(lnk.length>0?lnk:"");

		this.loaded[i]=0;

	}

    

    //An offset is added to the width of the grid output div, depending on the browser

	switch(this.browser()){

		case 'ff':

		case 'op':

			var hOffset = 40;

			break;

		case 'ie':

			var hOffset = 38;

			break;

		case 'moz':

		case 'saf':

		case 'unknown':

		default:

			var hOffset = 36;

			break;

	}

	

	var tmp_width = parseInt(gridWidth) * parseInt(this.grid_config['img_width'])+hOffset;

	

	//If we have position cookies then use their values, otherwise use the default position from the config

	if (this.windowPos()==''){

		var tmp_style = 'top: '+this.grid_config['pos_y']+'px; left: '+this.grid_config['pos_x']+'px;';

	} else {

		var tmp_style = this.windowPos();

	}

	

	output +='<div id="vidsec_output" style="'+tmp_style+' visibility: hidden; width: '+tmp_width+'px; background-color: '+this.grid_config['grid_bgcolor']+'; " onkeypress="if(event.keyCode == 27){imgSec.hide(); return false;}" >';

   	output +='<div class="vidsec_close" ><img src="'+VIDOOP_IMGROOT+'vidsec_grid_close_tab.gif" onclick="imgSec.hide();"/></div>';

   	output +='<div style="height:18px;background-color:'+this.vidsec_gridcolor.value+';cursor:move" id="vidsec_move_window"></div>';

	output +='<div style="border-top:0;border-right:18px solid '+this.vidsec_gridcolor.value+';border-left:18px solid '+this.vidsec_gridcolor.value+';border-bottom:18px solid '+this.vidsec_gridcolor.value + '" id="vidsec_output_border">';
//	output +='<div id="vidsec_output_border">';
	output+='<div id="vidsec_images">';

	if(this.grid_config['stitched'] == 'true'){

        // Draw one image

		var stitched_width = parseInt(this.grid_config['img_width']) * parseInt(gridWidth);

		var stitched_height = parseInt(this.grid_config['img_height']) * parseInt(gridHeight);

        //Set up styling as though there will only be the stitched grid (i.e. no popups)

		var stylestr = "style='position:relative;top:0;left:0;'";
		
		//Load stitched image grid

		var imgstr = '<img src="'+VIDOOP_WEBROOT+AUTHCORE_SCRIPT+ '?'+this.request_string+'='+this.handler_string['get_stitched_image']+'&'+this.param_string['user_id']+'=' + this.vidsec_user.value.replace(/"/g,"&#34;") + '&'+this.param_string['stitched_image_identifier']+'='+stitched_image_identifier+'" onload="imgSec.gridMakeVisible();" />';

 	var popups = "";

       	if(this.grid_config['popups']=="true"){

			//Reset styling

			stylestr = "";

			for(var i=0;i<image_identifiers.length;i++){

			//individual images

				popups +='<span class="vidsec_pair" id="vidsec_pair'+i+'" style="width:'+this.grid_config['img_width']+'px;height:'+this.grid_config['img_height']+'px;">';

				//image mouseovers

				if(image_descriptions[i] != ''){

					var bgstr = VIDOOP_WEBROOT+AUTHCORE_SCRIPT+ '?'+this.request_string+'='+this.handler_string['get_image']+'&'+this.param_string['user_id']+'=' + this.vidsec_user.value.replace(/"/g,"&#34;") + '&'+this.param_string['image_identifier']+'='+image_identifiers[i];

					var prevstr = '<div class="vpreview" id="preview'+i+'" onclick=\'window.open(\"'+image_links[i]+'\")\' onmouseout=\'document.getElementById("auth_code").focus()\' onmouseover=\'imgSec.getImagePopupData('+i+');document.getElementById("auth_code").blur()\' style="padding-top:'+(20+parseInt(this.grid_config['img_height']))+'px;width:'+(parseInt(this.grid_config['img_width']) + (this.browser()=='ie'?40:0))+'px;background-image:url(\''+bgstr+'\');background-repeat: no-repeat; background-position: 10px 10px;"><span class="vpreview_placeholder" style="background-image:url(\''+bgstr+'\');" ></span>' +  image_descriptions[i]+'</div>';

					var hoverstr = '<a href="#" class="pv"><img src="'+VIDOOP_WEBROOT+'images/blank.gif" style="width:'+this.grid_config['img_width']+'px;height:'+this.grid_config['img_height']+'px;"/>' + prevstr + '</a>';

					popups += hoverstr;

				}

				popups += '</span>';				

			}

	    }

		output +='<div id="vidsec_stitched_image" '+ stylestr +'>' + imgstr +'<!--&nbsp;--></div>';

		output += popups;

	}
	else {

		//Load individual images

	   	

	    for(var i=0;i<image_identifiers.length;i++){

	       	var imgstr='<img src="'+VIDOOP_WEBROOT+AUTHCORE_SCRIPT+ '?'+this.request_string+'='+this.handler_string['get_image']+'&'+this.param_string['user_id']+'=' + this.vidsec_user.value.replace(/"/g,"&#34;") + '&'+this.param_string['image_identifier']+'='+image_identifiers[i]+'" onload=\"imgSec.loadedImage('+i+');\" />'; 

	       	output+='<span class="vidsec_pair" id="vidsec_pair'+i+'" style="width:'+this.grid_config['img_width']+'px;height:'+this.grid_config['img_height']+'px;">';

	       	if(this.grid_config['popups']=="true"){

				//image mouseovers

				if(image_descriptions[i] != ''){

					var bgstr = VIDOOP_WEBROOT+AUTHCORE_SCRIPT+ '?'+this.request_string+'='+this.handler_string['get_image']+'&'+this.param_string['user_id']+'=' + this.vidsec_user.value.replace(/"/g,"&#34;") + '&'+this.param_string['image_identifier']+'='+image_identifiers[i];

					var prevstr = '<div onclick=\'window.open(\"'+image_links[i]+'\")\' onmouseout=\'document.getElementById("auth_code").focus()\' onmouseover=\'imgSec.getImagePopupData('+i+');document.getElementById("auth_code").blur()\' class="vpreview" id="preview'+i+'" style="padding-top:'+(20+parseInt(this.grid_config['img_height']))+'px; width:'+(parseInt(this.grid_config['img_width']) + (this.browser()=='ie'?40:0))+'px;background-image:url(\''+bgstr+'\');background-repeat: no-repeat; background-position: 10px 10px;">' +  image_descriptions[i]+'</div>';

					var hoverstr = '<a href="#" class="pv">' + imgstr + prevstr + '</a>';

					output += hoverstr;

				}else{

					output+=imgstr;

				}

	       	}else{

				output+=imgstr;

	       	}

			output+= '</span>';

	    }

	}

	//End of vidsec_images div

	output +='</div>';

    //Add the lower pane containing the input fields

	output+='<div id="vidsec_lower">';

    output+='<div id="vidsec_fields" style="display: none; width: '+(gridWidth * this.grid_config['img_width'] / 2+30) +'px; opacity: '+this.grid_config['grid_alpha']/100+'; filter: alpha( opacity = '+this.grid_config['grid_alpha']+' ); ">';

    output+='<br/>';
    
    output +='<span class="vidsec_field">'+ACCESS_CODE_FIELD_TITLE+' <input type="password" name="auth_code" id="auth_code" size="20" maxlength="15" onkeypress="return imgSec.catchkey(\'submitAuthGrid\',event);" onkeydown="return imgSec.catchkey(\'submitAuthGrid\',event);"></span>';

    output+='<br/>';
    
    output +='<span class="vidsec_field"><input type="button" id="vidsec_submit" value="'+LOGIN_BUTTON_TITLE+'" onclick="imgSec.submitAuthGrid();"></span>';

    output+='</div>';

    output+='<div id="seclogo"><img src="'+VIDOOP_WEBROOT+this.grid_config['logo']+'"/></div>';

    
    tmp_width = gridWidth * this.grid_config['img_width'];

	output+='<div id="vidsec_processing" style="margin-right: '+tmp_width/4+'px; margin-left: '+tmp_width/4+'px;">';

	//output+='<img src="'+VIDOOP_WEBROOT+'img/imageAuthentication/vidsec_grid_loading.gif" alt="loading" /> Processing...';
	//output +='<img src="'+VIDOOP_WEBROOT+'images/vidsec_grid_loading.gif" alt="loading" /> '+PROCESSING_MESSAGE;

	output+='</div>';
	
	//output +='<div class="vidsec_field" style="margin:5px;float:left;"><a href="#" onclick="imgSec.forgotCategories();">'+FORGOT_CATEGORIES_LINK+'</a></div>';

   // output+='<div class="vidsec_field" style="margin:5px;"><a href="vidsec_image_copyrights.html" target="_blank">Copyright information</a></div>';
   //output +='<div class="vidsec_field" style="margin:5px;float:right;"><a href="vidsec_image_copyrights.html" target="_blank">'+COPYRIGHT_INFO_LINK+'</a></div>';

    output +='</div>';
    
    
    //End of vidsec_output_border

    output +='</div>';

    

    //End of vidsec_output

    output +='</div>';

    
    //Draw the grid and make it draggable

    this.divContainer.innerHTML = output;
    
	this.makeDraggable( document.getElementById('vidsec_move_window'), document.getElementById('vidsec_output'), 2 );

}

imgSecurity.prototype.getImagePopupData = function(num){

    if(true === image_mouseover[num])

        return;

    this.ajax.onSuccess = function(){

        image_mouseover[num] = true;

    };

    this.ajax.execute(VIDOOP_WEBROOT + AUTHCORE_SCRIPT + '?' + this.request_string + '=' + this.handler_string['register_image_hover'] + '&' + this.param_string['user_id'] + '=' + this.vidsec_user.value + '&' + this.param_string['image_identifier'] + '=' + image_identifiers[num] + '&lang=' + this.language);

}


//Prompts user to select an offband channel, through which they will receive their authentication code

imgSecurity.prototype.selectOffbandChannel = function(xmlNode) {

	var output = '';

	output += '<div id="vidsec_token_enroll" style="'+this.windowPos()+'">';

    //output += '  <div class="vidsec_close" ><a href="#" id="vidsec_close_popup" onclick="imgSec.hide();">['+CLOSE_WINDOW_LINK+' &times;]</a></div>';
	
	output += '		<div class="vidsec_close" ><img src="'+VIDOOP_WEBROOT+'img/imageAuthentication/vidsec_grid_close_tab.gif" onclick="imgSec.hide();"/></div>';

	output += '     <div class="vidsec_move_window" id="vidsec_move_window"></div>';

	output += '		<div id="vidsec_llogo"></div>';

	output += '		<div id="vidsec_token_enroll_c">';

    output += '			<div style="margin-bottom:15px;">'+CHANNEL_SELECT_TITLE+'</div>';

	output += '			<div style="margin-bottom:15px;">'+CHANNEL_SELECT_TEXT+'<span class=tooltip><img class="question" src="'+VIDOOP_WEBROOT+'images/vidsec_grid_question.jpg" onmouseover="imgSec.showToolTip(\'number_tooltip\',\''+CHANNEL_SELECT_HELPTEXT+'\',450);" onmouseout="imgSec.hideToolTip(\'number_tooltip\');"><span class="answer_box" id=number_tooltip></span></span></div>';

	output += '			<div style="margin-bottom:15px;"><select id="ob_channel"></select><input type="button" id="vidsec_submit" value="'+SUBMIT_BUTTON_TITLE+'" onclick="imgSec.getObPass();"></div>';
	
	output += '			<div id="obMessageAlert" style="display:none;"><img src="'+VIDOOP_IMGROOT+'vidsec_grid_loading.gif" alt="loading" /> '+SENDING_CODE_TEXT+'</div>';

    output += '			<div><a href="javascript: imgSec.passwordPrompt(true);" class="vidsec_link">'+ALREADY_HAVE_CODE_TEXT+'</a></div>';

	output += '		</div>';

	output += '</div>';

	

	//Draw the prompt box and make it draggable

	this.divContainer.innerHTML = output;

	this.makeDraggable( document.getElementById('vidsec_move_window'), document.getElementById('vidsec_token_enroll') );

	

	//Create an <option> tag for each available channel, and insert it into the select box

	for(i=0;i<xmlNode.childNodes.length;i++){

	    var node=xmlNode.childNodes[i];

	    if(node.nodeName == this.param_string["token_id"]){

	        this.setToken(getNodeText(node));

	        continue;

	    }

	    if(node.nodeName != "channel"){

	        continue;

	    }

	    var channel_id = xmlNodeValue("channel_identifier",node);

	    var channel_description = xmlNodeValue("channel_description",node);

	    var tmp = document.createElement('option');

	    tmp.innerHTML = channel_description;

	    tmp.setAttribute("value",channel_id);

	    document.getElementById('ob_channel').appendChild(tmp);

	}

}

//Alternate version of selectOffbandChannel for users who have forgotten their image categories

imgSecurity.prototype.categoryResetSelectChannel = function(xml){

    var output = '';

    output += '<div id="vidsec_reenroll" style="'+this.windowPos()+'">';

    output += '  <div class="vidsec_close" ><a href="#" id="vidsec_close_popup" onclick="imgSec.hide();">['+CLOSE_WINDOW_LINK+' &times;]</a></div>';

    output += '     <div class="vidsec_move_window" id="vidsec_move_window"></div>';

    output += '		<div id="vidsec_llogo"></div>';

    output += '		<div id="vidsec_token_enroll_c">';

    output += '			<div style="margin-bottom:15px;" id="vidsec_reset_msg"></div>';

    output += '			<div id="vidsec_email" style="display:none;"><div id="ob_channel_email_title" style="margin-bottom:15px;font-weight:bold;">'+RESET_LINK_DEST_TEXT+'</div>';

    output += '			<div style="margin-bottom:15px;"><select id="ob_channel_email"></select></div></div>';

    output += '			<div id="vidsec_phone" style="display:none;"><div style="margin-bottom:15px;font-weight:bold;">'+RESET_CODE_DEST_TEXT+'</div>';

    output += '			<div style="margin-bottom:15px;"><select id="ob_channel_phone"></select></div></div>';

    output += '         <div id="vidsec_submitbtn"><input type="button" value="'+SUBMIT_BUTTON_TITLE+'" onclick="imgSec.getCategoryResetCode();"></div>';

    output += '		</div>';

    output += '</div>';

    	

    //Draw the prompt box and make it draggable

    this.divContainer.innerHTML = output;

    this.makeDraggable( document.getElementById('vidsec_move_window'), document.getElementById('vidsec_reenroll') );

    	

    //Create an <option> tag for each available channel, and insert it into the appropriate select box

    //var xml = this.responseXML.firstChild;

    var num_email = 0;

    var num_phone = 0;

    var msg;

    var divEmail = document.getElementById('vidsec_email');

    var divPhone = document.getElementById('vidsec_phone');

    for(var i=0;i<xml.childNodes.length;i++){

        var node=xml.childNodes[i];

        var sel;

        switch(node.nodeName){

            case "email_channels":

                sel = document.getElementById('ob_channel_email');

                num_email++;

                break;

            case "phone_channels":

                sel = document.getElementById('ob_channel_phone');

                num_phone++;

                break;

            default:

                continue;

                break;

        }

        for(var t=0; t<node.childNodes.length;t++){

            var subnode = node.childNodes[t];

            var channel_id = xmlNodeValue("channel_identifier",subnode);

            var channel_description = xmlNodeValue("channel_description",subnode);

            if(!channel_id || !channel_description)continue;

            var tmp = document.createElement('option');

            tmp.innerHTML = channel_description;

            tmp.setAttribute("value",channel_id);

            sel.appendChild(tmp);

        }

    }

	    

    //Display appropriate message

    if(num_email > 0 && num_phone > 0){

        msg = RESET_MESSAGE_BOTH;

        divEmail.style.display="";

        divPhone.style.display="";

    }else if(num_email > 0 && num_phone < 1){

        msg = RESET_MESSAGE_EMAIL;

        document.getElementById('ob_channel_email_title').innerHTML = RESET_CODE_DEST_TEXT;

        divEmail.style.display="";

    }else if(num_email < 1 && num_phone > 0){

        msg = RESET_MESSAGE_PHONE;

        divPhone.style.display="";

    }else if(num_email < 1 && num_phone < 1){

        msg = RESET_MESSAGE_ABORT;

    }

    document.getElementById('vidsec_reset_msg').innerHTML = msg;

}



imgSecurity.prototype.forgotCategories = function(){

    var me = this;

    this.ajax.onSuccess = function(){

        var node = this.responseXML.firstChild;

        if(node.nodeName == me.response_tags['channel_list'])

            me.categoryResetSelectChannel(node);

        else

            me.handleResponse(node);

	}

	

	this.ajax.execute(VIDOOP_WEBROOT + AUTHCORE_SCRIPT + '?' + this.request_string + '=' + this.handler_string['forgot_categories'] + '&' + this.param_string['user_id'] + '=' + this.vidsec_user.value + '&lang=' + this.language);

}



imgSecurity.prototype.getCategoryResetCode = function(){

    var me = this;

    var channel_identifier;

    var divEmail = document.getElementById('ob_channel_email');

    var divPhone = document.getElementById('ob_channel_phone');

    

    if(divEmail.value.length > 0 && divPhone.value.length > 0){

        channel_identifier = divEmail.value + "|" + divPhone.value;

    }else if(divEmail.value.length > 0){

        channel_identifier = divEmail.value;

    }else if(divPhone.value.length > 0){

        channel_identifier = divPhone.value;

    }else

        return;

    

    var me = this;

    this.ajax.onSuccess = function(){

        me.handleResponse(this.responseXML.firstChild);

    }

    this.ajax.execute(VIDOOP_WEBROOT + AUTHCORE_SCRIPT + '?' + this.request_string + '=' + this.handler_string['category_reset_select_channel'] + '&' + this.param_string['user_id'] + '=' + this.vidsec_user.value + '&' + this.param_string['channel_identifier'] + '=' + channel_identifier + '&lang=' + this.language);

}



imgSecurity.prototype.categoryResetCodePrompt = function(xml){

    var type = xmlNodeValue("type", xml);

    var msg, title;

    switch(type){

        case "phone":

            title = RESET_TITLE_PHONE;

            msg = RESET_NOTIFY_PHONE;

            break;

        case "email":

            title = RESET_TITLE_EMAIL;

            msg = RESET_NOTIFY_EMAIL;

            break;

        case "both":

            title = RESET_TITLE_EMAIL;

            msg = RESET_NOTIFY_BOTH;

            break;

    }

    var output = '';

	output += '<div id="vidsec_reenroll" style="'+this.windowPos()+'">';

	output += '  <div class="vidsec_close" ><a href="#" id="vidsec_close_popup" onclick="imgSec.hide();">['+CLOSE_WINDOW_LINK+' &times;]</a></div>';

	output += '     <div class="vidsec_move_window" id="vidsec_move_window"></div>';

	output += '		<div id="vidsec_llogo"></div>';

	output += '		<div id="vidsec_token_enroll_c">';

	output += '			<div style="margin-bottom:15px;font-weight:bold">'+title+'</div>';

	output += '			<div style="margin-bottom:15px;" id="vidsec_reset_msg">'+msg+'</div>';



	if(type == "phone" || type == "email"){

	    output += '     <div><input type="password" id="vidsec_password" onkeypress="return imgSec.catchkey(\'submitObPass\',event);" onkeydown="return imgSec.catchkey(\'submitObPass\',event);"/>';

	    output += '  	     <input type="button" onmousedown="" value="'+SUBMIT_BUTTON_TITLE+'" onclick="imgSec.submitPassword(true);"></div>';

        output += '     <div id="vidsec_processing" style="margin-top:10px;margin-bottom:-10px;">';

    	output += '       <img src="'+VIDOOP_IMGROOT+'vidsec_grid_loading.gif" alt="loading" /> '+PROCESSING_MESSAGE;

    	output += '     </div>';

	}

	output += '		</div>';

	output += '</div>';

	

	this.divContainer.innerHTML = output;

	this.makeDraggable( document.getElementById('vidsec_move_window'), document.getElementById('vidsec_reenroll'));

}








//Tells the server which channel the user chose to get their offband password through, replaces the channel prompt with an input for the password

imgSecurity.prototype.getObPass = function() {

	var me = this;

	this.ajax.onSuccess = function () {

 		me.handleResponse(this.responseXML.firstChild);

 		var notoken = false;

 		try{

 		    notoken = (this.responseXML.firstChild.firstChild.nodeName == "notoken");

 		}catch(e){}

   		imgSec.passwordPrompt(true, notoken);

	};

	alertBox = document.getElementById('obMessageAlert');

	alertBox.style.display = "";
	
	this.obChannelIdentifier = document.getElementById('ob_channel').value;

    this.ajax.execute(VIDOOP_WEBROOT + AUTHCORE_SCRIPT + '?' + this.request_string + '=' + this.handler_string['offband_select_channel']+ '&' + this.param_string['user_id'] + '=' + this.vidsec_user.value + '&' + this.param_string['channel_identifier'] + '=' + this.obChannelIdentifier + '&lang=' + this.language);

}



//Displays a password prompt (behavior is slightly different depending on whether the prompt is for an offband password)

imgSecurity.prototype.passwordPrompt = function(obpass, notoken){

    var prompt_label = (obpass?CODE_FIELD_TITLE:PASSWORD_FIELD_TITLE);

    var submitAction = (obpass?"submitObPass":"submitPassword");

	var tmp_checked = (this.vidsec_remember==true?'checked="checked"':'');

	

	var output = '';

	output += '<div id="vidsec_key_confirm" style="'+this.windowPos()+'" >';

    //output += '  <div class="vidsec_close" ><a href="#" id="vidsec_close_popup" onclick="imgSec.hide();">['+CLOSE_WINDOW_LINK+' &times;]</a></div>';
	output += '  <div class="vidsec_close" ><img src="'+VIDOOP_WEBROOT+'img/imageAuthentication/vidsec_grid_close_tab.gif" onclick="imgSec.hide();"/></div>'

	output += '  <div class="vidsec_move_window" id="vidsec_move_window"></div>';

	output += '  <div id="vidsec_key_confirm_c">';

	output += '   	  <div class="vidsec_bold">'+prompt_label+':</div>';

    output += '   	  <div><input type="password" id="vidsec_password" onkeypress="return imgSec.catchkey(\''+submitAction+'\',event);" onkeydown="return imgSec.catchkey(\''+submitAction+'\',event);"/>';
	
    output += '  	       <input type="button" onmousedown="" id="vidsec_submit" value="'+SUBMIT_BUTTON_TITLE+'" onclick="imgSec.submitPassword('+(obpass?'true':'false')+');"></div>';

	output += '  	  <div id="error_message" style="display:none;" class="error_message"></div>';

	if(!notoken){

	    output += '  	  <div style="margin-top: 10px;">';

        output += '            <span class="check_box" onclick="imgSec.toggleRemembered();" onkeypress="return imgSec.catchkey(\''+submitAction+'\',event);">';

	    output += '                 <input id="vidsec_remember" '+tmp_checked+' type="checkbox" onclick="imgSec.toggleRemembered();" onkeypress="return imgSec.catchkey(\''+submitAction+'\',event);">';

        output += '                 <span class="check_box_label">'+REMEMBER_ME_TITLE+'</span>';

	    output += '            </span>';

	    output += '            <span class="tooltip"><img class="question" src="'+VIDOOP_WEBROOT+'images/vidsec_grid_question.jpg" onmouseover="imgSec.showToolTip(\'tooltip\',\''+REMEMBER_ME_HELPTEXT+'\',350);" onmouseout="imgSec.hideToolTip(\'tooltip\');"><span class="answer_box" id=tooltip></span></span>';

	    output += '       </div>';

	}

    output += '       <div id="vidsec_processing" style="margin-top:10px;margin-bottom:-10px;">';

	output += '         <img src="'+VIDOOP_IMGROOT+'vidsec_grid_loading.gif" alt="loading" /> ' + PROCESSING_MESSAGE;

	output += '       </div>';

	output += '  	  <div class="line_break" style="margin-bottom:15px;"> </div>';

    if(!obpass)

	    output += '       <div><a href="#" onclick="imgSec.forgotPassword();">'+FORGOT_PASSWORD_LINK+'</a></div>';

	output += '  </div>';

	output += '</div>';

	

	//Display the prompt box, give focus to the input, and make the box draggable

	this.divContainer.innerHTML = output;

	document.getElementById('vidsec_password').focus();

	this.makeDraggable( document.getElementById('vidsec_move_window'), document.getElementById('vidsec_key_confirm') );
	
	//Start checking for the OB password status

	if (obpass)

	    this.obStatusInterval = setInterval("imgSec.checkOBPasswordStatus()", 2000);

}

//Pops up an error dialog if an OB password fails to be sent

imgSecurity.prototype.checkOBPasswordStatus = function(){

    var me = this;

	this.ajax.onSuccess = function () {

        var status = "";	

	    try {

 		    status = getNodeText(this.responseXML.firstChild.firstChild);

 		} catch (e) {}

 		if (status != "IN_PROGRESS")

 		    clearInterval(me.obStatusInterval);

 		if (status == "FAILED")

            me.showToolTip('vidsec_error', ERR_OFFBAND_GET_SEND_STATUS, 350, 'error', null, null, 'imgSec.lock(false)');

	};

	this.ajax.execute(VIDOOP_WEBROOT + AUTHCORE_SCRIPT + '?' + this.request_string + '=' + this.handler_string['offband_get_status']+ '&' + this.param_string['user_id'] + '=' + this.vidsec_user.value + '&' + this.param_string['channel_identifier'] + '=' + this.obChannelIdentifier + '&lang=' + this.language);

}




//Displays a prompt for the user to submit a new password

imgSecurity.prototype.changePasswordPrompt = function(){

	var output = '';

	output += '<div id="vidsec_password_change" style="'+this.windowPos()+'" >';

	output += '  <div class="vidsec_close" ><img src="'+VIDOOP_WEBROOT+'img/imageAuthentication/vidsec_grid_close_tab.gif" onclick="imgSec.hide();"/></div>'

	output += '  <div class="vidsec_move_window" id="vidsec_move_window"></div>';

	output += '  <div id="vidsec_password_change_c">';

    output += '   	  <div class="vidsec_bold">'+NEW_PASSWORD_FIELD_TITLE+'</div>';

	output += '   	  <div><input type="password" id="vidsec_new_password"/></div>';

	output += '   	  <div class="vidsec_bold">'+CONFIRM_PASSWORD_FIELD_TITLE+'</div>';
	
	output += '   	  <div><input type="password" id="vidsec_new_password_confirm"/></div>';

	output += '  	  <div><input type="button" onmousedown="" value="'+SUBMIT_BUTTON_TITLE+'" onclick="imgSec.submitNewPassword();"></div>';

	output += '  	  <div id="error_message" style="display:none;" class="error_message"></div>';

    output += '       <div id="vidsec_processing" style="margin-top:10px;margin-bottom:-10px;">';

	output += '         <img src="'+VIDOOP_IMGROOT+'vidsec_grid_loading.gif" alt="loading" /> ' + PROCESSING_MESSAGE;

	output += '       </div>';

	output += '  	  <div class="line_break" style="margin-bottom:15px;"> </div>';

	output += '  </div>';

	output += '</div>';

	

	//Display the prompt box, give focus to the input, and make the box draggable

	this.divContainer.innerHTML = output;

	document.getElementById('vidsec_new_password').focus();

	this.makeDraggable( document.getElementById('vidsec_move_window'), document.getElementById('vidsec_key_confirm') );

}



imgSecurity.prototype.submitNewPassword = function(){

    var pass = document.getElementById('vidsec_new_password').value;

    var confirm = document.getElementById('vidsec_new_password_confirm').value;

    

    if(pass.length < 1){

        this.showToolTip('vidsec_error', ERR_ENTER_PASSWORD, 402, 'error', null, null, null);

        return;

    }

    if(pass !== confirm){

        this.showToolTip('vidsec_error', ERR_PASSWORD_MISMATCH, 402, 'error', null, null, null);

        return;

    }


    var me = this;

    this.ajax.onSuccess = function(){

        me.handleResponse(this.responseXML.firstChild);

    }

    
    this.ajax.execute(VIDOOP_WEBROOT + AUTHCORE_SCRIPT + '?' + this.request_string + '=' + this.handler_string['reset_password'] + 

        '&' + this.param_string['user_id'] + '=' + this.vidsec_user.value + 

        '&' + this.param_string['password'] + '=' + document.getElementById('vidsec_new_password').value + '&lang=' + this.language);
        

}



//Toggles the "vidsec_remember" property, which determines if a token should be deposited upon successful authentication of a password or activation number

imgSecurity.prototype.toggleRemembered = function(){

	var element = document.getElementById('vidsec_remember');

	if (!element.checked){

		this.vidsec_remember=true;

		element.checked = true;

	} else {

		this.vidsec_remember=false;

		element.checked = false;

	}

	

}



//Submits the password to the server for validation

imgSecurity.prototype.submitPassword = function(obpass) {

    var handler = (obpass?this.handler_string['offband_auth']:this.handler_string['password_auth']);

    var me = this;



    this.ajax.onSuccess = function () {

        me.handleResponse(this.responseXML.firstChild);

    };

    var url = VIDOOP_WEBROOT + AUTHCORE_SCRIPT + '?' + this.request_string + '=' + handler + 

        '&' + this.param_string['user_id'] + '=' + this.vidsec_user.value + 

        '&' + this.param_string['password'] + '=' + document.getElementById('vidsec_password').value + 

       '&' + this.param_string['token_deposit'] + '=' + this.vidsec_remember +

        '&lang=' + this.language;

        this.ajax.execute(url);

        document.getElementById('vidsec_processing').style.visibility = 'visible';

}



//Begins a password retrieval

imgSecurity.prototype.forgotPassword = function(){

    var me = this;

    this.ajax.onSuccess = function(){

        //var result = getNodeText(this.responseXML.firstChild);

        //me.showToolTip('vidsec_error', result);

        me.handleResponse(this.responseXML.firstChild);

    }

    this.ajax.execute(VIDOOP_WEBROOT + AUTHCORE_SCRIPT + '?' + this.request_string + '=' + this.handler_string['forgot_password'] + '&' + this.param_string['user_id'] + '=' + this.vidsec_user.value + '&lang=' + this.language);

}



//Erases the grid

imgSecurity.prototype.hide = function(){

    this.divContainer.innerHTML = "";

    this.lock(false);

}



//Displays a message (such as an error) in a popup div

imgSecurity.prototype.showToolTip = function(element,msg,width,classname,tmp_top,tmp_left,func){

    
    
    if(element=="lblLogonInfo")
    {
      var lblLogInfo=document.getElementById(element);
      this.hideToolTip('vidsec_error');
      lblLogInfo.innerText=document.getElementById('hdnImgAuthConfigError').value;
      return;
      
    }
    
	var container = document.getElementById(element);

	

	if(tmp_top!=undefined){

		vOffSet = "top:"+tmp_top+"px;";

	} else {

		vOffSet = "";

	}

	

	if(tmp_left!=undefined){

		hOffSet = tmp_left;

	} else {		

		var pos = Array();

		tmp_pos = findPos(container);

		if(tmp_pos[0]!=0) {

			var pos = tmp_pos[0];

			this.pop_up_pos = tmp_pos[0];

		} else {

			var pos = this.pop_up_pos;

		}

		var xpos = pos+parseInt(width);

		var bwidth = this.browserSize('width')-45;

	

		if(xpos > bwidth){

			hOffSet = (xpos - bwidth)*-1;

		} else {

			hOffSet = 3;

		}

	}

	

	if(classname=='error'){

		var close_btn = '<br/><a id="error_close_btn" style="-moz-outline:0;color:blue;" href="#" onclick="imgSec.hideToolTip(\'vidsec_error\',\''+func+'\')">'+CLOSE_WINDOW_LINK+'</a>';

		

		if(tmp_top==undefined)

			vOffSet = "top:"+(this.startY-235)+"px;";

		else

			vOffSet = "top:"+(this.startY-tmp_top)+"px;";

			

		if(tmp_left==undefined)

			hOffSet = this.startX-66;

		else

			hOffSet = this.startX-tmp_left;

			

		if(this.browser()=='ie'){

			hOffSet -= 74;

		}

		try{

		    document.getElementById('vidsec_processing').style.visibility = 'hidden';

		}catch(e){}

	} else {

		var close_btn = '';

	}



	var output = "";

	output += '<div id="vidsec_msg" class="answer" style="width:'+width+'px;top:'+vOffSet+'px;left:'+hOffSet+'px;"  onclick="imgSec.hideToolTip(\''+element+'\',\''+func+'\')">';

	output += '     <div class="answer_border_top vidsec_transparent"> </div>';

	output += '     	<table width="100%" cellpadding=0 cellspacing=0><tr>';

	output += '              <td class="answer_border_left vidsec_transparent"></td>';

	output += '              <td class="answer_text">'+msg+close_btn+'</td>';

	output += '              <td class="answer_border_left vidsec_transparent"></td>';

	output += '         <tr></table>';

	output += '     <div class="answer_border_top vidsec_transparent"> </div>';

	output += '</div>';

	container.innerHTML = output;

	container.style.display = "";


	//Make sure the message box stays in the window

	var msgBox = document.getElementById('vidsec_msg');

    if(hOffSet < this.windowLeft)

        msgBox.style.left = this.windowLeft + "px";

    if(vOffSet < this.windowTop)

        msgBox.style.top = this.windowTop + "px";

    


	if(classname=='error')

		document.getElementById("error_close_btn").focus();

}



//Erases the tooltip box

imgSecurity.prototype.hideToolTip = function(element,func){

	var container = document.getElementById(element);

	container.innerHTML = "";

	container.style.display = "none";

	if(func!=undefined)

		eval(func);

}



//Shows or hides the 'Loading...' image, according to state

imgSecurity.prototype.loading = function(state){

    
    if(state){
    
        this.startX=450;
        this.startY=120;

		output = '';

		output += '<div id="vidsec_loading" class="vidsec_hide" style="'+this.windowPos()+'">';
		
		this.startX=0;
        this.startY=0;

		if (this.grid_config['stiched_images'] == false) {

			output += '     <img src="'+VIDOOP_IMGROOT+'vidsec_grid_loading.gif" alt="loading" /> '+LOADING_MESSAGE+'<span id="vidsec_progress">0</span>%';

		}

		else {
		    

            output += '     <img src="'+VIDOOP_IMGROOT+'vidsec_grid_loading.gif" alt="loading" /> '+LOADING_MESSAGE+'<span id="vidsec_progress"></span>';							

		}

		output += '</div>';

        this.divLoader.innerHTML = output;

		this.divLoader.style.display="block";

		

	    for (var i=0; i < this.grid_config['gridsize']; i++)

        	this.loaded[i] = 0;

    } else {

        this.divLoader.style.display="none";

		this.progress = 0;

        this.showProgress(this.progress);

    }

}



//Displays progress of grid loading

imgSecurity.prototype.showProgress = function(iProgress) {

	document.getElementById('vidsec_progress').innerHTML = iProgress;	

}



//Field validation

imgSecurity.prototype.validateField = function (data){

	regex = /(<|>|%|\\|#|\^|&|\$|'|")/;

	if (String(data).search(regex) != -1) return false; // field doesn't validate if regex pattern matches

	else return true;

}



//Displays the popup panel for the selected image

imgSecurity.prototype.preview = function(num){

    if(image_descriptions[num].length < 1)

        return;

    var obj = document.getElementById('preview' + num);

    if(obj.innerHTML.length <= 1){

       this.loading(true);

       var output = '';

       var imgTag = '<img onLoad="imgSec.loading(false);" class="vpreviewimg" src="'+VIDOOP_WEBROOT+AUTHCORE_SCRIPT+ '?'+this.request_string+'='+this.handler_string['get_image']+'&'+this.param_string['user_id']+'=' + this.vidsec_user.value + '&'+this.param_string['image_identifier']+'='+image_identifiers[num]+'" style="width:'+this.grid_config['preview_width']+'px; height:'+this.grid_config['preview_height']+'px;" />';

       output += (image_links[num]!=""?'<a href="javascript: imgSec.newWindow('+num+');">'+imgTag+'</a>':imgTag);

       output += "<p>"+image_descriptions[num]+"</p>";

       obj.innerHTML = output; 

       obj.style.display="inline";

    } else {

       obj.style.display="inline";

    }

}



//Create a popup window corresponding to the preview image that was clicked

imgSecurity.prototype.newWindow = function(num){

    var newWindow = window.open(image_links[num]);

    //Remark the below to do new window as a popunder

    //newWindow.blur();

    //window.focus();

}



//Listens to keypresses, executes corresponding function when Enter is pressed

imgSecurity.prototype.catchkey = function(action, e){

    var Key = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;

    switch(action){

        case 'submitUserID':

            if(Key == 13){

                if(!this.dirty){

        	        this.submitUserID();

        	        this.dirty = true;

	            }

                return false;

            }else{

                this.dirty = false;

            }

            break;

        case 'submitAuthGrid':

            if(Key == 13){

                if(!this.dirty){

        	        this.submitAuthGrid();

        	        this.dirty = true;

	            }

                return false;

            }else{

                this.dirty = false;

            }

            break;

        case 'submitObPass':

            if(Key == 13){

                if(!this.dirty){

        	        this.submitPassword(true);

        	        this.dirty = true;

	            }

                return false;

            }else{

                this.dirty = false;

            }

            break;

        case 'submitPassword':

            if(Key == 13){

                if(!this.dirty){

        	        this.submitPassword(false);

        	        this.dirty = true;

	            }

                return false;

            }else{

                this.dirty = false;

            }

            break;

    }

}



//Used to prevent a new grid fetch from being started while a previous one is in progress

imgSecurity.prototype.lock = function(state){

    this.locked = state;

    //this.vidsec_login.disabled = state;

    try{

        this.vidsec_card_login.disabled = state;

    }

    catch(e){}

}

//Used to fetch the middle part of the cookie/swfobject's name (will be prefixed by config value and suffixed with browser name)

imgSecurity.prototype.getTokenName = function(){

    this.ajax.execute(VIDOOP_WEBROOT + AUTHCORE_SCRIPT + '?' + this.request_string+'='+this.handler_string['get_token_name']+'&'+this.param_string['user_id']+'='+ this.vidsec_user.value + '&lang=' + this.language, false);

    this.token_name = this.token_prefix+xmlNodeValue("token_name",this.ajax.responseXML); 

}



//Deposits an authentication token (both a cookie and a Flash Shared Object are created)

imgSecurity.prototype.setToken = function(tokenID,func){

	if(this.token_name == ""){

    	 this.ajax.execute(VIDOOP_WEBROOT + AUTHCORE_SCRIPT + '?' + this.request_string+'='+this.handler_string['get_token_name']+'&'+this.param_string['user_id']+'='+ document.getElementById("vidsec_user").value+ '&lang=' + this.language, false);
    	 this.token_name = this.token_prefix+xmlNodeValue("token_name",this.ajax.responseXML);
	}

    

    var tn = this.token_name + '_' + this.browser();

    

    //Set cookie token

    try{

        var date = new Date();

        date.setTime(date.getTime() + 1000 * 60 * 60 * 24 * 365)

        var expDate = date.toGMTString();

        var cookieString = tn+'=' + escape(tokenID) + '; path=/; expires=' + expDate +';';

        document.cookie = cookieString;

    }catch(e){

        //console.log("Failed to set cookie:"+e);

    }

	    

	//Set SWF token

	try{

	    this.swf_token.SetVariable('tokenName',tn);

	    this.swf_token.SetVariable('newTokenID',tokenID);

	}catch(e){

	    //console.log('Failed to set shared object:'+e);

	}

			

	if(func != undefined && func != '')

	   	eval(func); 

}



//Look for cookie token and SWF token

//If only one is present, then return its value

//If both are present and they match, return the shared value

//If both are present but they do not match, return blank string 

imgSecurity.prototype.getToken = function(){ 

    var token = '';

    var cookie_token = null;

    var swf_token = 'undefined';

    var tn = this.token_name + '_' + this.browser();

    

    try{

        //Get value from cookie

        cookie_token = cookieVal(tn);

    }catch(e){

		//console.log('Failed to get cookie');

	}

    try{

        //Get value from SWF object

        imgSec.swf_token.SetVariable('tokenName', tn);

        swf_token = imgSec.swf_token.GetVariable('tokenID');

    }catch(e){

		//console.log('Failed to get flash object:'+e);

	}

    //Compare values

    if(cookie_token != null && swf_token != 'undefined'){

        if(cookie_token == swf_token)

            token = cookie_token;

        else

            removeToken();

    }else if(cookie_token == null && swf_token != 'undefined'){

        token = swf_token;

    }else if(cookie_token != null && swf_token == 'undefined'){

        token = cookie_token;

    }

    return token;

}



imgSecurity.prototype.removeToken = function(tokenName){

    tokenName += '_' + this.browser();

    //Delete the cookie

    try{

        document.cookie = tokenName + '=; expires=Thu, 01-Jan-1970 00:00:01 GMT';

    }

    catch(e){

        //console.log('Failed to delete cookie: '+e);

    }

    //Delete the SWF token

    try{

        //temp measure: blank out the token ID until I can get back into the swf's source code to do a clear() on the shared object

        this.swf_token.SetVariable('tokenName',tokenName);

	    this.swf_token.SetVariable('newTokenID','');

    }

    catch(e){

        //console.log('Failed to delete SWF object: '+e);

    }

}



//Redirects to appropriate page, based on final result of login attempt

imgSecurity.prototype.processLoginResult = function(node) {

    if (xmlNodeValue(this.response_tags['login_result'] + '.result_state', node.parentNode) == "success") {

        //window.location = this.successURL;
        //window.location=this.vidsec_successURL.value;
        window.location = "../authenticated/ImageBasedAuth_Redirect.aspx?vAuthSuc=1";

    } else {

        if (node.getElementsByTagName('token_remove').length > 0)

            this.removeToken(this.token_name);

        //if (this.failureURL=='') {

        //	tmp_top = parseInt(this.grid_config['grid_height']-1)*this.grid_config['img_height']*-1+75;

        //	tmp_left = Math.round(this.grid_config['grid_width']*this.grid_config['img_width']/2)*-1+150+30;

        //	this.showToolTip('vidsec_error','<strong>Login Failed</strong>',300,'error',tmp_top,tmp_left,'this.hide();this.lock(false);this.vidsec_login.focus();');

        //} else

        //window.location.href = this.vidsec_failureURL.value;

        window.location.href = '../community/Login.aspx?vAuthFailed=1&error=Image Based Login Failed';
    }

}



imgSecurity.prototype.gotoEnroll = function(){

    var token_deposit = 'false';

    try{

        if(document.getElementById('vidsec_remember').checked)token_deposit = 'true';

    }catch(e){}

    //window.location=this.enrollURL + '?vidsec_user=' + this.vidsec_user.value + '&' + this.param_string['token_deposit'] + '=true';
   // window.location=this.enrollURL + '?vidsec_user=' + this.vidsec_user.value + '&' + this.param_string['token_deposit'] + '=' + token_deposit + '&lang=' + this.language;
    window.location=this.enrollURL;

}



// Determine the user's brower width or height (type)

imgSecurity.prototype.browserSize = function(type){

	if(type == 'width'){

		return window.innerWidth != null? window.innerWidth : document.documentElement && document.documentElement.clientWidth ?       document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null;;

	} else {

		return window.innerHeight != null? window.innerHeight : document.documentElement && document.documentElement.clientHeight ?  document.documentElement.clientHeight : document.body != null? document.body.clientHeight : null;

	}                   

}



// Determines browser

imgSecurity.prototype.browser = function(){

	var d, dom, ie, ie4, ie5x, moz, mac, win, lin, ie5mac, ie5xwin, op, ns, ff;



	d = document;

	n = navigator;

	na = n.appVersion;

	nua = n.userAgent;

	win = ( na.indexOf( 'Win' ) != -1 );

	mac = ( na.indexOf( 'Mac' ) != -1 );

	lin = ( nua.indexOf( 'Linux' ) != -1 );



	if ( !d.layers ){

		dom = ( d.getElementById );

		op = ( nua.indexOf( 'Opera' ) != -1 );

		konq = ( nua.indexOf( 'Konqueror' ) != -1 );

		saf = ( nua.indexOf( 'Safari' ) != -1 );

		moz = ( nua.indexOf( 'Gecko' ) != -1 && !saf && !konq);

		ff = (nua.indexOf('Firefox')!= -1);

		ie = ( d.all && !op );

		ie4 = ( ie && !dom );

	

		/*

		ie5x tests only for functionality. ( dom||ie5x ) would be default settings. 

		Opera will register true in this test if set to identify as IE 5

		*/

	

		ie5x = ( d.all && dom );

		ie5mac = ( mac && ie5x );

		ie5xwin = ( win && ie5x );

		

	} else {

		ns = true;

	}

	

	if ( ie ) {

		return 'ie';

	} else if ( ff ) {

		return 'ff';

	} else if ( konq ){

		return 'konq';

	} else if ( ns ){

		return 'ns';

	} else if ( op ){

		return 'op';

	} else if ( saf ){

		return 'saf';

	} else if ( moz ){

		return "moz";

	} else {

		return "unknown";

	}

}



/******************************************************************

* Helper functions for window dragging

******************************************************************/



imgSecurity.prototype.makeDraggable = function(item,pWindow,winTop){

	var me = this;

	if(!item) return;

	item.onmousedown = function(ev){

		if(winTop!=undefined){

			me.windowTop = winTop;	

		}		

		me.dragObject  = pWindow;

		me.mouseOffset = me.getMouseOffset(pWindow, ev);

		return false;

	}

}



imgSecurity.prototype.getMouseOffset = function(target, ev){

	ev = ev || window.event;



	var docPos    = this.getPosition(target);

	var mousePos  = this.mouseCoords(ev);

	return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};

}



imgSecurity.prototype.mouseCoords = function(ev){

	if(ev.pageX || ev.pageY){

		return {x:ev.pageX, y:ev.pageY};

	}

	return {

		x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,

		y:ev.clientY + document.body.scrollTop  - document.body.clientTop

	};

}



imgSecurity.prototype.getPosition = function(e){

	var tmp_left = 0;

	var tmp_top  = 0;



	while (e.offsetParent){

		tmp_left += e.offsetLeft;

		tmp_top  += e.offsetTop;

		e     = e.offsetParent;

	}



	tmp_left += e.offsetLeft;

	tmp_top  += e.offsetTop;



	return {x:tmp_left, y:tmp_top};

}



imgSecurity.prototype.windowPos = function(){	

	if ( this.startX>=0 && this.startY>=17 ){

		return 'top:'+this.startY+'px;left:'+this.startX+'px;';

	} else {

		return tmp_style = '';

	}

}



imgSecurity.prototype.mouseUp = function(ev){

	var me = imgSec;

	me.dragObject = null;

	//save position for next session

	try{

        var date = new Date();

        date.setTime(date.getTime() + 1000 * 60 * 60 * 24 * 365)

        var expDate = date.toGMTString();

        var cookieStringX = 'vidoop_window_x=' + me.startX + '; path=/; expires=' + expDate +';';

		var cookieStringY = 'vidoop_window_y=' + me.startY + '; path=/; expires=' + expDate +';';

        document.cookie = cookieStringX;

		document.cookie = cookieStringY;

    }catch(e){

		//console.log("Failed to set cookie:"+e);

	}

}



imgSecurity.prototype.mouseMove = function(ev){

	var me = imgSec;

	ev           = ev || window.event;

	var mousePos = me.mouseCoords(ev);

	if(me.dragObject){

		me.dragObject.style.position = 'absolute';

		var tmp_top = mousePos.y - me.mouseOffset.y;

		var tmp_left = mousePos.x - me.mouseOffset.x;

		//protect top

		if (tmp_top>me.windowTop) {

			me.dragObject.style.top       = tmp_top;

			me.startY = tmp_top;

		}

		//snap top

		if (tmp_top<me.windowTop+me.windowSnap){

			me.dragObject.style.top       = me.windowTop;

			me.startY = me.windowTop;

		}

		//protect left

		if(tmp_left>me.windowLeft){

			me.dragObject.style.left      = tmp_left;

			me.startX = tmp_left;

		}

		//snap left

		if(tmp_left<me.windowSnap){

			me.dragObject.style.left      = me.windowLeft;

			me.startX = me.windowLeft;

		}		

		/*

		//protect right

		if(tmp_left>me.browserSize('width')-me.dragObject.offsetWidth+me.windowOffset){

			me.dragObject.style.left = me.browserSize('width')-me.dragObject.offsetWidth+me.windowOffset;

			me.startX = me.browserSize('width')-me.dragObject.offsetWidth+me.windowOffset;

		}

		//snap right

		if(tmp_left>me.browserSize('width')-me.dragObject.offsetWidth+me.windowOffset-me.windowSnap){

			me.dragObject.style.left = me.browserSize('width')-me.dragObject.offsetWidth+me.windowOffset;

			me.startX = me.browserSize('width')-me.dragObject.offsetWidth+me.windowOffset;

		}

		//protect bottom

		if(tmp_top>me.browserSize('height')-me.dragObject.offsetHeight+me.windowOffset){

			me.dragObject.style.top = me.browserSize('height')-me.dragObject.offsetHeight+me.windowOffset;

			me.startY = me.browserSize('height')-me.dragObject.offsetHeight+me.windowOffset;

		}

		//snap bottom

		if(tmp_top>me.browserSize('height')-me.dragObject.offsetHeight+me.windowOffset-me.windowSnap){

			me.dragObject.style.top = me.browserSize('height')-me.dragObject.offsetHeight+me.windowOffset;

			me.startY = me.browserSize('height')-me.dragObject.offsetHeight+me.windowOffset;

		}*/



		return false;

	}

}



/******************************************/

/*Class for making and handling AJAX calls*/

/******************************************/

function imgSecAjax() {

	

}



imgSecAjax.prototype.oAjax = function(){

  if(typeof XMLHttpRequest != "undefined"){

        return new XMLHttpRequest();

    } else if(window.ActiveXObject) {

        var ver = ["MSXML2.XMLHttp.5.0",

                   "MSXML2.XMLHttp.4.0",

                   "MSXML2.XMLHttp.3.0",

                   "MSXML2.XMLHttp",

                   "Microsoft.XMLHttp"];

        for(var i=0;i<ver.length;i++){

            try{

                return new ActiveXObject(ver[i]);

                break;

            } catch (err) {}

        }

    }

    return;

}



//Checks to see if call is complete, if so it collects response data and calls onSuccess function

imgSecAjax.prototype.readyState = function(obj) {
   if(obj.readyState==4 && obj.status==200){

       this.responseText = obj.responseText;

       this.responseXML = obj.responseXML;

       this.onSuccess();

   }

}



//Creates a request object and makes call to passed url

imgSecAjax.prototype.execute = function(url, async) {
    if(undefined===async)

        async=true;

    this.responseText = "";

    var ajaxObj = this.oAjax();

    var me = this;

    if(async)

        ajaxObj.onreadystatechange = function() { me.readyState(ajaxObj) };

	if(typeof(WCH) == "string")

        url += '&wch='+WCH;

    ajaxObj.open("GET", url, async);

    ajaxObj.send(null);

    if(!async){

        this.responseText = ajaxObj.responseText;

        this.responseXML = ajaxObj.responseXML;

    }

    return; 

}



//Creates a request object and makes call to passed url

imgSecAjax.prototype.executePost = function(url, vars) {

    this.responseText = "";

    var ajaxObj = this.oAjax();

    var me = this;

    //if(async)

        ajaxObj.onreadystatechange = function() { me.readyState(ajaxObj) };

    ajaxObj.open("POST", url, true);

    ajaxObj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

    ajaxObj.send(vars);

    //this.responseText = ajaxObj.responseText;

    //this.responseXML = ajaxObj.responseXML;

    return; 

}



/******************************************/

/*Helper functions                        */

/******************************************/



//Returns the X and Y coordinates of an object

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

		}

		this.curleft = curleft;

		this.curtop = curtop;

	} else {

		curleft = this.curleft;

		curtop = this.curtop;

	}

	return [curleft,curtop];

}



//Trim function

function trim(str)

{

   return str.replace(/^\s*|\s*$/g,"");

}



//Simple inArray function, checks to see if pVal exists anywhere in pArray

function inArray(pArray,pVal){

    for(var i=0; i<pArray.length; i++){

        if(pArray[i]==pVal){

            return true;

        }

    }

    return false;

}



//Returns text content of an XML node

function getNodeText(obj){

	if(obj && obj.textContent)

		return obj.textContent;

	else if(obj && obj.text)

		return obj.text;

	else if(obj && obj.firstChild)

	    return obj.firstChild.nodeValue;

	else

		return false;

}



//Gets the text content of an XML node in a specified descendant path from a base node

function xmlNodeValue(path, obj){

	var pathNodes=path.split('.');

	var topNode=obj.getElementsByTagName(pathNodes[0]);

	var lastNode = topNode[0];

	for(var i=1;i<pathNodes.length;i++){

		var list=lastNode.getElementsByTagName(pathNodes[i]);

		lastNode=list[0];

	}

	return getNodeText(lastNode);

}



//Returns value of cookie by given name

function cookieVal(cookieName){

    var cookie_list = document.cookie;

    var list = cookie_list.split(";");

    for(var i=0;i<list.length;i++){

        var this_cookie = trim(list[i]).split('=');

        if(this_cookie[0]==cookieName){

            return unescape(this_cookie[1]);

            break;

        }

    }

    return null;

}



function URLEncode (clearString) {

  var output = '';

  var x = 0;

  clearString = clearString.toString();

  var regex = /(^[a-zA-Z0-9_.]*)/;

  while (x < clearString.length) {

    var match = regex.exec(clearString.substr(x));

    if (match != null && match.length > 1 && match[1] != '') {

    	output += match[1];

      x += match[1].length;

    } else {

      if (clearString[x] == ' ')

        output += '+';

      else {

        var charCode = clearString.charCodeAt(x);

        var hexVal = charCode.toString(16);

        output += '%' + hexVal.toUpperCase();

      }

      x++;

    }

  }

  return output;

}


