/**
 * General KC Functions: Signin, Background Swapping, 
 * Implements functionality for the signin
 * 
 * @author Sean Hsieh <sean@envsn.com>
 * @author Charlie Tran <charlie@transvalence.com>
 * @author David Martin <david@transvalence.com>
 */



var _isErrored = false;	//is the login form in an error state
var _loggedIn = false;	//is the user logged in
var _errorMsgDelay = 3;   //how long to show error message in seconds
		// _signinOriginalWidth: $('signin').getWidth(),
		
var member = null;		//Stores member info object after authentication

function _bind()
{
 if ($('signout')) {
 
 $('signout').observe('click', signout);
 }
}
/* Signin */

document.observe('dom:loaded', _bind);

/**
 * Handles display of authentication error message to user
 * @param {string} message Error message
 */
function displayAuthError(message) 
{
_isErrored = true;
$('statusText').addClassName('error');
$('statusText').innerHTML = message;
$('statusText').show();
Effect.Fade('statusText', { 
duration:2,
delay: _errorMsgDelay,
queue: {position:'end', scope: 'authError'}
});
}


/**
 * On successfull server response to Ajax request this  determines if 
 * the actual authentication attempt was successfull. Because of the
 * fixed nature of the memeber login process, the repsonse of this ajax
 * request is an HTML page that must be parsed down and searched to
 * determin authentication result.
 * @param {Object} transport XmlHttpRequest object
 */
function handleAuthentication(transport) 
{
var resp = transport.responseText;
var respElem = document.createElement('div'); //create an element that we can embed HTML into for easier manipulation
respElem.innerHTML = resp.substring( resp.indexOf('<body>')+6 ,resp.indexOf('</body>') );

var heading = false; //This whole process is a work around for IE
$(respElem).descendants().each(function(element){
if(element.id=="heading") {
	heading = element.innerHTML;
}
});

if ( heading && heading.indexOf('errors') == -1) {
authSuccess();
} else {
var content = '';
$(respElem).descendants().each(function(element){
	if(element.id=="content") {
		content = element.getElementsByTagName('li')[0].innerHTML;
	}
});
displayAuthError( content );	
}
}

/**
 * Handles errors thrown by the the Ajax request. Determines if the error
 * was an expection (internal to XHR, like invalid JSON parse) or if the
 * server threw an error (generally when the status code != 200)
 * @param {Object} transport XmlHttpRequest object
 * @param {Object} e Exception object
 */
function authFailure(transport, e) 
{
//alert('signout failure');
//console.log("auth failure: "+transport.status);
if (e) {	//If this exists then XHR threw an exception
displayAuthError('Exception: ' + e.message);	
} else {	//Server must have done something funky
displayAuthError('('+transport.status +') '+ transport.statusText);
}
}


/**
 * Pings the server for authentication and defines the callbacks based
 * on server response.
 * @param {Object} event Prototype event object
 */
function authenticate(event) 
{
//console.log('authenticate');
//this.stopTimer();
// event.stop(); //prevent form form actually submitting

$('kc_login_form').request({
onSuccess: handleAuthentication,
onFailure: authFailure,
onException: authFailure
});
}

//var kc = (typeof kc == 'undefined') ? [] : kc;


//kc.signinSearch = {
function initialize() 
{
        
		
		$('statusText').hide();
		//console.log('statusText bind');
		//bind RPX button events
		//$('fb_button').observe('click', fb_click);
		//$('aol_button').observe('click', aol_click);

 //old member vars
 
}		
		
		
		/**
		 * Figure out what to when signin / signout button is clicked. There
		 * are 3 states of the button each of which need their own handlers:
		 * 	1) signin with form closed 
		 * 	2) signin with form open 
		 * 	3) signout
		 * @param {Object} event Prototype event object
		 */
function dispatchClick(event) 
{
	event.target.blur();
	if (_loggedIn) {       //if logged in then do signout
		signout();
	} else if (_isOpen) { //if form fields showing then submit form
		authenticate(event);
	} else {                                     //else show the form fields
		expand(); 
	}
}
		

		

		

		
		/**
		 * Handles display of authentication success message to user
		 * @param {string} message Success message
		 */
		
function displaySuccessMsg(message) 
{
    $('statusText').removeClassName('error');
    $('statusText').innerHTML = message;
    $('statusText').show();
	Effect.Fade('statusText', { 
		duration:2,
		delay: _errorMsgDelay,
		queue: {position:'end', scope: 'authError'}
	});
}
		
		/**
		 * Handles the DOM update to display a logged in state
		 */
function authSuccess() 
{			
	signin._isErrored = false;
	setLoggedInStatus(true);
	$('PageWrapper').innerHTML += '<form method="post" id="dummyForm1" name="dummyForm1"></form>';
    parent.document.dummyForm1.submit();  
    // $('statusText').hide();
    // $('statusText').removeClassName('error');
    // showLoggedInPanels();
	
	
}
		
function showLoggedInPanels() 
{
			if($('KCSignIn'))
			  {
		       $('KCSignIn').hide();
			  }
            if($('profile'))
		      {
               $('profile').show();
		      }
            
			$('signout').show();
			$('signout').observe('click', signout);
			
			if($('commentInputWrapper'))
			  {
			   panels.commentPanel.revealCommentForm();
			  }
			if($('register')) 
			  {
			   $('register').hide();
			  }
		}
		
function hideLoggedInPanels() 
{
		    //$$('#KCSignIn')[0].show();
		    $('profile').hide();
			$('signout').hide();
			$('SigninBtn').show();
			
			if ($('commentInputWrapper')) {panels.commentPanel.hideCommentForm();}
			if ($('register')) {$('register').show();}
			
			//bind RPX button events
			//$('fb_button').observe('click', fb_click);
			//$('aol_button').observe('click', aol_click);
		}
		
		/**
		 * Preforms the various updates that corrospond to changing a users status
		 * @param {boolean} loggedInStatus True if user is logged in, otherwise false
		 */
function setLoggedInStatus(loggedInStatus) 
{
			_loggedIn = loggedInStatus;
			if (loggedInStatus) {
				getMemberInfo();
                // showLoggedInPanels();
			} else {
				member = null;
			}
		}
		
		/**
		 * Requests information for the current users
		 */
function getMemberInfo() 
{
			//console.log('getMemberInfo');
		    ko = new Date();
		    ji = ko.getTime();
			new Ajax.Request( '/index.php/kc/member_info_json?nocache='+ji, {
				method: 'get',
				onSuccess: updateMemberInfo,
				onFailure: authFailure,
				onException: authFailure
			});
		}
		
		/**
		 * Updates the local member object with the requested member information
		 * @param {Object} transport XmlHttpRequest object
		 */
function updateMemberInfo(transport) 
{
	member = transport.responseText.evalJSON();
	displaySuccessMsg("Welcome, "+member.userName);
}
		
		/**
		 * Handles user signout requests. Verfies that the user actually wants
		 * to sign out and peforms the sign out ajax request.
		 */
function signout() 
{
			if(confirm("Are you sure you want to sign out?") ) 
			  {
			   //didn't like creating a new attribute for <a>
			   //time in seconds.. really should make that server side
			   //console.log("going to perform AJAX signout...");
		       var now = new Date();
			   var time = now.getSeconds();
			   var url = '/index.php?ACT=10&nocache='+time;
			   var req = new Ajax.Request( url, {
					method: 'post',
					onSuccess: handleSignout,
					onFailure: authFailure,
					onException: authFailure
				});
			}
		}
		
		/**
		 * On successfull server response to Ajax request this  determines if 
		 * the actual signout attempt was successfull. Because of the
		 * fixed nature of the memeber signout process, the repsonse of this ajax
		 * request is an HTML page that must be parsed down and searched to
		 * determin result.
		 * @param {Object} transport XmlHttpRequest object
		 */
function handleSignout(transport) 
{
	//console.log("handleSignout");
	var resp = transport.responseText;
	var respElem = document.createElement('div'); //create an element that we can embed HTML into for easier manipulation
	respElem.innerHTML = resp.substring( resp.indexOf('<body>')+6 ,resp.indexOf('</body>') );
	
	var heading = false; //This whole process is a work around for IE
	$(respElem).descendants().each(function(element){
		if(element.id=="heading") {
			heading = element.innerHTML;
		}
	});
	
	if( heading && heading.indexOf('errors') == -1) 
	  {
		//console.log('signout success');
		signoutSuccess();
	  }
	else 
	  {
		//console.log('signout failure');
		var content = '';
		$(respElem).descendants().each(function(element){
			if(element.id=="content") {
				content = element.getElementsByTagName('li')[0].innerHTML;
			}
		});
		displayAuthError( content );	
	}
}
		
		/**
		 * Handles the DOM update to display a logged out state
		 */
function signoutSuccess() 
{
	setLoggedInStatus(false);
	$('PageWrapper').innerHTML += '<form method="post" id="dummyForm1" name="dummyForm1"></form>';
    parent.document.dummyForm1.submit();
	// $('signout').hide();
	//$$('#KCSignIn #EE FORM INPUT[name="password"]')[0].value=''; //Dump the password value in the form to be safe
    // hideLoggedInPanels();
}
	






/* End Signin */

/* Password Toggle Scripts */

function togglePassword() {
	var passwordInput = $('password');
	var parent_div = passwordInput.parentNode;
	var myForm = passwordInput.form;
	var passwordField;
	
	if (passwordInput.readAttribute('type') == 'password') {
		if (passwordInput.value === '') {
			passwordInput.remove();
			passwordField = new Element("INPUT", {
				'type': 'text',
				'value': 'Password',
				'name': 'password',
				'class': 'field',
				'id': 'password',
				'onFocus': 'togglePassword()'
			});
			parent_div.insert({bottom:passwordField});
		}
	}
	else {
		if (passwordInput.value == 'Password' && passwordInput.readAttribute('type') == 'text') {
			passwordInput.remove();
			passwordField = new Element("INPUT", {
				'type': 'password',
				'value': '',
				'name': 'password',
				'class': 'field',
				'id': 'password',
				'onBlur': 'togglePassword()',
				'style': 'color: #000'
			});
			parent_div.insert({bottom:passwordField});
			passwordField.focus();
		}
	}
}
function toggleEmpty(initialValue, element) {
	if (element.value == initialValue) {
		element.value = '';
	}
}
function toggleFill(initialValue, element) 
{
	if (element.value === '') {
		element.value = initialValue;
	}
}

function getMyKoldcast()
{
	var player = getMovieName("kc_player");
	player.getMyKoldcast();
}

function updatePanels(videoId)
{
	//alert("updatePanels: "+videoId);
	//kc.panels.hideAll();
	kc.panels.setEntryId(videoId);
	//kc.panels.show();
}


function select_all(obj)
{ 
 var text_val=eval(obj);
 text_val.focus();
 text_val.select();
 if(!document.all) 
   { 
	return; // IE only
   }
 r = text_val.createTextRange();
 r.execCommand('copy');
}

/* End Password Toggle Scripts */

/* RPX scripts */
/*function fb_click()
{
 //Modalbox.show("/rpx/fb_load.php", {title: 'Connect with Facebook', width: 980, height: 610});
 //var fb_url = 'https://koldcast.rpxnow.com/facebook/start?token_url=http://dev.koldcast.tv:8080/rpx/rpx_login.php';
 
 //window.open(fb_url,'Conect with Facebook', 'width=980,height=610,menubar=yes,status=yes, location=yes,toolbar=yes,scrollbars=yes');
}

function aol_click()
{
 Modalbox.show("/rpx/aol_load.php", {title: 'Connect with AOL', width: 400, height: 300});
 //$("aol_form_button").observe("click", aol_form_submit); 
}

function aol_form_submit()
{
 var identifier = $("aol_identifier").value + $("aol_sn").value;
 
 //alert(identifier);
 $("aol_identifier").value = identifier;
 $("aol_form").request({
       onComplete: function()
       { 
        console.log("complete!");
        var html = this.responseText; 
        console.log(html);
        $('aol_container').innerHTML = html;
       }
     });
	
}*/