/* main object works like a controller calls a factory and a event class */
function main( s_objname_fp ){

	this.o_construct = __construct;
	this.o_factory; 
	this.s_objname;
	this.o_attach;

	function __construct(){
		/* instanciating factory to create lang , gallery , form , acctuil */
		this.o_factory = new factorycreateobjs();
		/* calling attachEventObjs  */
		this.o_attach = new attachEventObjs( this.o_factory );
		return this.o_factory;
	}

	function setCallBack( s_objname_fp ){
		/* keeps a reference of its self*/
		this.s_objname = s_objname_fp;
	}

}

function attachEventObjs( o_main_fp ){
	/* this is a event binder more object could be attach to this array as needed*/
	this.o_main_fp = o_main_fp;
	this.a_object_holder = new Array();

	this.a_object_holder["login"] = new loginEvent(  this.o_main_fp );
	this.a_object_holder["register"] = new registerEvent( this.o_main_fp );
	this.a_object_holder["download"] = new downloadEvent( this.o_main_fp );
	this.a_object_holder["gallery"] = new galleryEvent( this.o_main_fp );
	this.a_object_holder["invite_code"]	= new invitecodeEvent( this.o_main_fp );
	this.a_object_holder["secret_game"] = new secretgameEvent( this.o_main_fp );
	this.a_object_holder["choose_country"] = new choosecountryEvent( this.o_main_fp );
	this.a_object_holder["choose-country"] = new trialAttachEvent();
	this.a_object_holder["trial"] = new trialEvent( );
	this.a_object_holder["prefs"] = new prefsEvent( this.o_main_fp );
	this.a_object_holder["tutorial"] = new tutorialEvent();
}

function factorycreateobjs(){
	/* this is the factory class that holds all objects need such as lang , util and ani that gallery needs, its all in one place more class and be added*/
	this.createobjs = createobjs;
	this.o_container = {}

	function createobjs(){
		this.o_container.lang = new createlang();
		this.o_container.util = new createutils();
		this.o_container.anim = new createanim();
		return this.o_container;
	}

}

function createlang(){
/* holds a pointer to accutil and returns it back to the factory */
	        // get the account utils loading in the background
        o_acctutil = new acctUtils('o_acctutil', s_interfacelangpath,
                        s_langlistpath, s_skinlistpath, s_langcode, DEF_SKINCOOKIE,
                        DEF_LANGCOOKIE, DEF_REGPATH, DEF_LOGINPATH, DEF_ACCTINFOPATH,
                        DEF_ACCTMAINTPATH);
        o_acctutil.setCtrlDivs(DEF_CTRLCOVER, DEF_CTRLDIALOG);
        return o_acctutil;
}

function createutils(){
	/* holds a pointer to Utils and returns it back to the factory */
	var o_utils = new siteUtils("o_utils");
	    return o_utils;
}

function createanim(){
/* holds a pointer to animation class and returns it back to the factory */
	var o_anim = new animObj('o_anim');
	    return o_anim;

}

/* on page complete window on loads calls a method with name declaration __call which 
	creates a pointer to the main object which creates a factory object , and calls attach events.
*/

var o_main; /* this is global incase some object outside the framework needs to use it, such as a function being called from html like onclick, onmouse etc*/

$( document ).ready( function(){
	forceSetUp();
	/* account trial or upgrade */
		accountUpgrade();
		accountEnterUpgrade();
		accountEnterSku();
		trialAttachTime();
		closeWindow();
		downloadLink();
});



window.onload = function(){ 
	 __call(); 
}

function __call(){
	o_main = new main("o_main");
	o_main.o_construct();
}


/* events start here which are called from attachEvent object */

function loginEvent( o_attachevent_fp ){
/* this object checks for login-btn id selector if found will  call doInitLoginForm which appends the login html form to div-ctrl*/
	if( $_("a-login") ){	
		$_("a-login").onclick = function(){ 
			$("#div-ctrlcover").animate({ "opacity":".7" },2000).css("display" , "block" );
			$("#div-ctrldialog,#div-ctrldialog-wrapper").animate({ "opacity":"1" },2000).css( "display" , "block" );
			 doInitLoginForm( o_attachevent_fp.createobjs().lang );
		 }
	}
	
	if( $_("img-calloutbottom") ){

		$_("img-calloutbottom").onclick = function(){ 
			if( obj.id ){	
				window.location = "?section=myepets3dtrial";
			}

			else{
				$("#div-ctrlcover").animate({ "opacity":".7" },2000).css("display" , "block" );
				$("#div-ctrldialog,#div-ctrldialog-wrapper").animate({ "opacity":"1" },2000).css( "display" , "block" );
			 	doInitLoginForm( o_attachevent_fp.createobjs().lang );
			}

		 }

	}

	if( $_("login-btn") ){
		$_("login-btn").onclick = function(){
			$("#div-ctrlcover").animate({ "opacity":".7" },2000);
			$("#div-ctrldialog,#div-ctrldialog-wrapper").animate({ "opacity":"1" },2000).css( "display" , "block" );
			 doInitLoginForm( o_attachevent_fp.createobjs().lang );
		}	
	}

	if( $_("welcome-create") ){
		$_("welcome-create").onclick = function(){
			welcomeMenu();
		}
	}
	
	if( $_("welcome-account-btn") ){
		$_("welcome-account-btn").onclick = function(){
			$("#div-ctrlcover").animate({ "opacity":".7" },2000);
			$("#div-ctrldialog,#div-ctrldialog-wrapper").animate({ "opacity":"1" },2000).css( "display" , "block" );
			 doInitLoginForm( o_attachevent_fp.createobjs().lang );
		}	
	}

}

function HTMLlogin(){
		$("#submit-login").click( function(){ 
			$.get( "?request=login&action=login&type=user&username="+ $("#in-a-txt").val() +"&password=" + $("#in-b-txt").val() + "" , { } , function( http ){
					if( http == 1 || http == "1") { 
						window.location = "";
					}
					else{ 
						alert("Please check your username and password.");
					}
			} );
		} );
}

function registerEvent( o_attachevent_fp ){
/* this object checks for register-btn id selector if found will call doInitRegForm which beings the registeration process*/
	if( $_("a-reg") ){
		$("#a-reg").click( function(){
			$("#div-ctrlcover").animate({ "opacity":".7" },2000);
			$("#div-ctrldialog,#div-ctrldialog-wrapper").animate({ "opacity":"1" },2000, function(){ 
				doInitRegForm( o_attachevent_fp.createobjs().lang );			
			}).css( "display" , "block" );
		} );
	}
	if( $_("register-btn") ){
		$_("register-btn").onclick = function(){
			$("#div-ctrlcover").animate({ "opacity":".7" },2000);
			$("#div-ctrldialog,#div-ctrldialog-wrapper").animate({ "opacity":"1" },2000, function(){ 
				doInitRegForm( o_attachevent_fp.createobjs().lang );			
			}).css( "display" , "block" );
		}
	}
	
	if( $_("welcome-register") ){
		$_("welcome-register").onclick = function(){
			welcomeMenu();
		}
	}

	if( $_("a-navreg") ){
		$_("a-navreg").onclick = function(){
			welcomeMenu();
		}
	}

	if( $_("welcome-span-create") ){
		$_("welcome-span-create").onclick = function(){
			$("#div-ctrlcover").animate({ "opacity":".7" },2000);

			$("#div-ctrldialog,#div-ctrldialog-wrapper").animate({ "opacity":"1" },2000, function(){ 
				doInitRegForm( o_attachevent_fp.createobjs().lang );			
			}).css( "display" , "block" );
		}
	}
}

function loginMenuEvent(){
/* this object checks for a-nav-login id selector if found will call dialogbox menu box */
			dialogBox();
			o_main.o_construct();
}

function downloadEvent( o_attachevent_fp ){
/* download event gets all elements that are anchors, looks for a occurance with fdownload in the element id string
	if found will continue through the loop then will attach the force download that also calls google.
*/
	if( $_("div-fun-box") ) {
		var elemList = document.getElementsByTagName("a");		
		for( var i = 0; i < elemList.length; i++ ){
			if( elemList[i].id.indexOf( "fdownload" ) > -1 ){
			
				elemList[i].onclick = function(){
					var a_intString = this.id.split("-"); 
					var s_int =  a_intString[ a_intString.length - 1 ];
					o_attachevent_fp.createobjs().util.doDownloadWindow("?request=download&id=" + s_int );
				}				

			}
			
		}
	}
}

function galleryEvent( o_attachevent_fp ){
	if( $_("div-products-box") ){
	// pub/lang/prod_gallery.js (and a_allprod therein) need to be available to
	// the calling page!
	var a_prod;
	var s_category;
	var s_season;
	
		s_category = o_attachevent_fp.createobjs().util.getUriValue(KEY_CATEGORY);
		s_season = o_attachevent_fp.createobjs().util.getUriValue(KEY_SEASON);
		o_anim = o_attachevent_fp.createobjs().anim;

		if (s_category === false) {
			s_category = DEF_PRODCAT;
		}
		if (s_season === false) {
			s_season = DEF_PRODSEASON;
		}	

		a_prod = myepetsHash.productGallery.a_allprod[s_season][s_category];
		o_gallery = new galleryObj(o_anim, 'o_gallery', a_prod, IMG_PRELDR,DEF_PUBPATH + s_langcode + '/' + DEF_INTRFCELANGPATH);
		o_gallery.doImgPreload();


	}
}

function invitecodeEvent( o_attachevent_fp ){
	/* this object here checks to see if there is a ?vite_code=( 32 length varchars ) param and arg in the uri , if so calls reg form  */
	if( o_attachevent_fp.createobjs().util.getUriValue(KEY_INVCODE).length == 32  ){
		doInitRegForm();
	}
}

function secretgameEvent( o_attachevent_fp ){
	if( $_("a-header-code") ){
		$_("a-header-code").onclick = function(){ accessGame( "bouncepounce" ); }
	}
	
	if( $_("a-fun-games1") ){
		$_("a-fun-games1").onclick = function(){ accessGame("bouncepounce"); }
	}
}

function choosecountryEvent( o_attachevent_fp ){
	if( $_("a-country") ){
		$_("a-country").onclick = function(){ o_attachevent_fp.createobjs().lang.doUserLangInterface(); }
	}
}


function doInitLoginForm( o_acctutil ) {
	/* this object creates a formObj for login*/
               o_loginform = new formObj('o_regform', o_acctutil.doUserLoginInterface , DEF_PUBPATH + s_langcode + '/' + DEF_INTRFCELANGPATH, '', '', '', '');
}

function doInitPasswordLookupForm() {
        o_regform = new formObj('o_regform', o_acctutil.doPasswordLookupInterface, DEF_PUBPATH + s_langcode + '/' + DEF_INTRFCELANGPATH, '', '', '', '');
}

function doInitRegForm() { 
/* this object creates a formObj for login*/
// this method gets called from acctutils if someone wants to register from login window so that o_form can be properly created
        o_regform = new formObj('o_regform', o_acctutil.doRegDOB, DEF_PUBPATH + s_langcode + '/' + DEF_INTRFCELANGPATH, DEF_PUBPATH + DEF_BADWORDPATH, DEF_TIMEPATH, DEF_PUBPATH + s_langcode + '/' + DEF_CNTRYLISTPATH, DEF_PUBPATH + s_langcode + '/' + DEF_STATELISTPATH);
}


function doInitAcctMaintForm( o_acctutil ) { // this gets called to get form params before showing the input for new values - callback is the method that open the inputs in o_acctutil
        o_regform = new formObj('o_regform', o_acctutil.getUserAcctInfo, DEF_PUBPATH + s_langcode + '/' + DEF_INTRFCELANGPATH, DEF_PUBPATH      + DEF_BADWORDPATH, '', '', '');
}

function dialogBox(){
/* this object insert the dialog box to div-ctrldialog wich is the menu login/registeration */
	if( $_("div-ctrldialog") ){
		$_("div-ctrlcover").style.display = "block";

    	 	$_("div-ctrldialog").style.display = "block";
     		$_("div-ctrldialog").innerHTML = "<div id=\"div-closebutton\"><a onclick=\"o_acctutil.doCloseCtrl();\" href=\"#\">[close]</a></div>";    
     		$_("div-ctrldialog").innerHTML += "<h4>" + myepetsHash.language.registration.introduction + "</h4>";
     		$_("div-ctrldialog").innerHTML += "<button id=\"login-btn\">" + myepetsHash.language.registration.login + "</button>";
     		$_("div-ctrldialog").innerHTML += "<button id=\"register-btn\">" + myepetsHash.language.registration.register + "</button>";
	}

}

function accessGame( s_secretgame ){
	var b_loggin = ( obj.id )? true : false;	
	
		if( b_loggin ){
			if( myepetsHash.secretGame[s_secretgame][2] ){
				var p_code = window.prompt( myepetsHash.language.fun.code );    
                        	if( p_code == myepetsHash.secretGame[s_secretgame][0] ){ 
					/* open the new window with uri */ 
					windowOpen( myepetsHash.secretGame[s_secretgame][1] , myepetsHash.secretGame[s_secretgame][3] , myepetsHash.secretGame[s_secretgame][4] );

				 }
                       		else if( p_code == null ){    /* this means they cancelled the window */ }    
                        	else { /* */ accessGame( s_secretgame ); }
			}
			
			else{
				windowOpen( myepetsHash.secretGame[s_secretgame][1] , myepetsHash.secretGame[s_secretgame][3] , myepetsHash.secretGame[s_secretgame][4] );
			}
		}
		
		else{ dialogBox(); o_main.o_construct(); }
} 

function windowOpen( s_uri , i_width , i_height ){
	window.open( s_uri  , "myWindow" , "location=0,status=0,scrollbars=0,width=" + i_width + " ,height=" + i_height + " " );
}

function $_( o_elementname_fp ){
	/* this object encapsulates get element by id*/
	return document.getElementById( o_elementname_fp );
}

function trialAttachTime(){
	if($("#p-overlay-create")){
		setTimeout(function(){trialAttachEvent()},"5000");
	}
}
	
function trialAttachEvent(){
	var elem_array = document.getElementsByTagName("a");
	for( var i = 0; i < elem_array.length; i++ ){
		 if( elem_array[i].id.indexOf("trial") > 1 ){
			bindMouseEvent( elem_array[i] , elem_array[i].id.substr( 8 ) );
			bindClickEvent( elem_array[i] , elem_array[i].id.substr( 8 ) );
		}
		if( elem_array[i].id.indexOf("pet") > 1 ){
			bindMouseEvent( elem_array[i] , elem_array[i].id.substr( 6 ) );	
		}
	}
}

function bindMouseEvent( o_elem , i_sku  ){

	o_elem.onmouseover = function(){
		showProductAttributes( myepetsHash.trialskus[i_sku] );	
	}

	o_elem.onmouseout = function(){
		hideProductAttributes();
	}
}

function bindClickEvent( o_elem , i_sku ){
	o_elem.onclick = function(){
		doAjaxPost( "?request=trial&userid=" + obj.id + "&sku=" + i_sku , function(){
				if( this.readyState == 4 ){
					alert( "Your trial account has been created" );
					window.location = "?section=myepets3dclouddownload";
				}
		 } );	
	}
	
}

function showProductAttributes( o_attributes ){
	if( $_("div-product-overlay") ){
			var div = $_("div-product-overlay");
			div.style.display = "block";
			div.innerHTML  = "<p class='p-product-attributes'>" + o_attributes.name + "</p>";
			div.innerHTML += "<p class='p-product-attributes'>Class: " + o_attributes.c_class + "</p>";
			div.innerHTML += "<p class='p-product-attributes'>Base Attributes:</p>";
			div.innerHTML +=  "<ul id='ul-product-attributes'>" + buildInnerHTML( o_attributes ) +  "</ul>"; 
	}
}

function buildInnerHTML( o_attributes ){
	var toString = "";
	    toString  = "<li><label class='label-left label-green-b'> ACC </label><label class='label-right label-green'>" + o_attributes.acc + " </label></li>";
	    toString += "<li><label class='label-left label-green-b'> HP </label><label class='label-right label-green'>"+ o_attributes.hp + "</label></li>";
	    toString += "<li><label class='label-left label-green-b'> SPD </label><label class='label-right label-green'>"+ o_attributes.spd + "</label></li>";
	    toString += "<li><label class='label-left label-blue-b'> EVA </label><label class='label-right label-blue'>"+ o_attributes.eva + "</label></li>";
	    toString += "<li><label class='label-left label-blue-b'> MDF </label><label class='label-right label-blue'>"+ o_attributes.mdf + "</label></li>";
	    toString += "<li><label class='label-left label-blue-b'> MP </label><label class='label-right label-blue'>"+ o_attributes.mp + "</label></li>";
	    toString += "<li><label class='label-left label-blue-b'> PDF </label><label class='label-right label-blue'>"+ o_attributes.pdf + "</label></li>";
	    toString += "<li><label class='label-left label-red-b'> INT </label><label class='label-right label-red'>"+ o_attributes.i_int + "</label></li>";
	    toString += "<li><label class='label-left label-red-b'> STR </label><label class='label-right label-red'>"+ o_attributes.str + "</label></li>";
	    toString += "<li><label class='label-left label-red-b'> TAL </label><label class='label-right label-red'>"+ o_attributes.tal + "</label></li>";
	return toString;
}

function hideProductAttributes( ){
	if( $_("div-product-overlay") ){
		 $_("div-product-overlay").style.display = "none"; 
	}
}

/* trial event object to attach on click to trial-btn id selector*/
function trialEvent(){
        if( $_("trial-btn") ){
                $_("trial-btn").onclick = function(){
                        ( obj.id ) ? window.location = "?section=myepets3dtrial" : loginMenuEvent(); 
                }
        }
}

function prefsEvent( o_attachevent_fp ){
	if( $_("a-prefs") ){
		$_("a-prefs").onclick = function(){
				doInitAcctMaintForm( o_attachevent_fp.createobjs().lang );
		}
	}
}

function welcomeMenu( ){
	                $_("welcome-board-wrapper").style.display = "none";
                        $_("welcome-menu").style.display = "block";
                        $_("welcome-board").style.backgroundImage = "url('smarty_files/templates/images/register_page_2.png')";
                        $_("welcome-board").style.width = "442px";
}

function forceLogin( s_username , s_password , request ){
	
	doAjaxPost( "?request=login&action=login&type=user&username=" + s_username + "&password=" + s_password + "&login_pref=" + request , function(){ 
			if( this.readyState == 4  ){
				window.location = "";
			}		
	});
}

function forceSetUp(){

	if( login_pref ){
		$("#div-ctrlcover").animate({ "opacity" : ".7" } , "2000" , function() { displayTemplate("myepets3d_overlay_" + login_pref + ".tpl"); }).css({"display" : "block"});
		
	}
}

function displayTemplate(template){
		$("#div-ctrldialog-wrapper").animate({ "opacity" : "1" } , "2000" ).css( "display" , "block");

		$("#div-ctrldialog").animate({ 
			"opacity" : "1" ,
			"width" : "750px" ,
			"height" : "400px"
		}  , "2000" , 
			function(){ 
			 	$( this ).load( "smarty_files/templates/static_tpl/" + template );
			}).css({ "display" : "block" });

}

function showDialogBox(){
		$("#div-ctrldialog").animate({ "opacity" : "1" } , "2000" ).css({ "display" : "block" });
}

function accountUpgrade(){
	if( $("#a-overlay-new") ){
		setTimeout( function(){ 

			$("#a-overlay-new , #a-start-new").click( function(){ 
				$("#div-register").animate({ "opacity" : "0" } , 1500 , function(){ 
					$( this ).css( { "display" : "none" } );
					$("#div-addnew").animate({"opacity" : "1"} , "slow" ).css({ "display" : "block" });
				} );
			}); 

			$("#a-overlay-upgrade , #a-continue").click( function(){ 
				$("#div-register").animate({ "opacity" : "0" } , 1500 , function(){ 
					$( this ).css( { "display" : "none" } );

					$("#div-addnew").animate({"opacity" : "1"} , "slow" ).css({ "display" : "block" });
					$("#a-overlay-add").css( "display" , "none" );
					$("#a-overlay-status-upgrade").css( "display" , "block" );
					$(".make-add").css( "left" , "15px" );

				} );
			}); 

		} , 7000);
	 }
} 

function accountEnterSku(){
	if( $("#a-overlay-add") ){
		setTimeout( function(){
			/* clear the input */
			$("#input-secret-code").click( function(){ 
					if( $( this ).val() == "Type your Secret Code here" ){
						$( this ).val( "" );
					}
			});

			/* ajax send sku */

			$("#a-overlay-add").click( function(){ 
				$.post( "?request=ajaxadd" , { "s_productkey" : $( "#input-secret-code" ).val() , "request" : "add" } , function( http ){
					var result = eval( '(' + http + ')' );


						switch( result[3] ){
							case 1 :
								showAddedPet();
								break;
							case 2 :
								$("#span-error").fadeIn("slow").html("Please try again, this product key is already in use.");
								break;
							case 3 :
								$("#span-error").fadeIn("slow").html("Please try again, this product key is invalid.");
								break;
						}

				});
			} );
		} , 5000 );
	}
}

function accountEnterUpgrade(){
	if( $("#a-overlay-status-upgrade") ){
	setTimeout(  function(){ 

			$("#input-secret-code").click( function(){
                                        if( $( this ).val() == "Input your Secret Code here." ){
                                                $( this ).val( "" );
                                        }
                        }); 

                        /* ajax send sku */

                        $("#a-overlay-status-upgrade").click( function(){ 

                                $.post( "?request=ajaxadd" , { "s_productkey" : $( "#input-secret-code" ).val() , "request" : "add" } , function( http ){

                                        var result = eval( '(' + http + ')' );

                                                switch( result[3] ){
                                                        case 1 : 
                                                                setAccountToFull( $( "#input-secret-code" ).val() );
                                                                break;
                                                        case 2 : 
                                                                $("#span-error").fadeIn("slow").html("Please try again, this product key is already in used.");
                                                                break;
                                                        case 3 : 
                                                                $("#span-error").fadeIn("slow").html("Please try again, this product key is invalid.");
                                                                break;
                                                }   

                                }); 
                        } );

		} , 5000 );
	}

}



function showAddedPet(){
				$("#div-addnew").animate({ "opacity" : "0" } , 1500 , function(){ 
					$( this ).css( "display" , "none"  );
					$("#div-congrats").animate({"opacity" : "1"} , "slow" ).css( "display" , "block" );
				} );
}

function setAccountToFull( s_productkey ){
		  var sku = s_productkey.substr( 0 , 6 );
		$.post( "?request=confirmajax" , { "product_key" : s_productkey , "user_id" : obj.id , "action" : "extend trial to full" , "sku" : sku } , function(){
				showAddedPet();
		 } );
}

function closeWindow(){
	if( $("#a-close-window" ) ){
		setTimeout( function() {
				$("#a-close-window").click( function(){
						window.location = "";
				 } );
		 } , 5000 );

	 }
}

function downloadLink(){

	if( $("#welcome-download") ){
		if( obj.id ){
			$("#welcome-download").click( function(){
					window.location = "?section=myepets3dclouddownload";
			});
		}
	}
}

function tutorialEvent(){
	if( $_("welcome-take") ){
		$_("welcome-take").onclick = function(){ tutwindow = window.open('smarty_files/templates/tutorial/','Tutorial','scrollbars=no,menubar=no,height=600,width=800,resizable=no,toolbar=no,location=no,status=no'); tutwindow.moveTo(100,100);}
	}
}	


