$( document ).ready( function(){ 
	jcarousel();
});

function $_( idSender ){
	return document.getElementById( idSender );
}

/* 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["login-menu"] = new loginMenuEvent( );
	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["video"]		= new videoEvent( );
	this.a_object_holder["videoplay"]	= new videoplayEvent();
	this.a_object_holder["links"]		= new linkEvents();
	this.a_object_holder["subcategory"]		= new subcategoryEvent( this.o_main_fp );
	this.a_object_holder["wishlist"]		= new wishlistEvent( this.o_main_fp );
	this.a_object_holder["frontgallery"]		= frontgallery( );
	this.a_object_holder["logout"]		= logoutEvent( );
}

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*/
window.onload = __call; 

function __call(){
	o_main = new main("o_main");
	o_main.o_construct();
	$("#p-login-area").css( { "visibility" : "visible" } );

	checkSecretCookieEnable();

}


/* 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(){ 
			 doInitLoginForm( o_attachevent_fp.createobjs().lang );
		 }
	}
	if( $_("login-btn") ){	
		$_("login-btn").onclick = function(){ 
			 doInitLoginForm( o_attachevent_fp.createobjs().lang );
		 }
	}
	/* country login*/
	if( $_("a-login-signin-btn-" + language ) ){
		$_("a-login-signin-btn-" + language ).onclick = function(){
			doInitLoginForm( o_attachevent_fp.createobjs().lang );
		}
	}
	

	
}

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-register") ){
		$_("a-register").onclick = function(){
			setTimeout( function() { 
				doInitRegForm( o_attachevent_fp.createobjs().lang );	
			} , 3000 );	
		}
	}
	
	if( $_("register-btn") ){
		$_("register-btn").onclick = function(){
			setTimeout( function() { 
				doInitRegForm( o_attachevent_fp.createobjs().lang );	
			} , 3000 );	
		}
	}
	/* country reg*/	
	if( $_("a-login-reg-btn-" + language ) ){
                $_("a-login-reg-btn-" + language ).onclick = function(){ 
			setTimeout( function() { 
				doInitRegForm( o_attachevent_fp.createobjs().lang );	
			} , 3000 );	
                 }   
        }   

}

function loginMenuEvent(){
/* this object checks for a-nav-login id selector if found will call dialogbox menu box */
	if( $_("a-nav-login" ) ){
		$_("a-nav-login").onclick = function(){
			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-gallery-box") ){
	// pub/lang/prod_gallery.js (and a_allprod therein) need to be available to
	// the calling page!
	var a_prod;
	var s_category;
	
		s_category = o_attachevent_fp.createobjs().util.getUriValue(KEY_CATEGORY);
		o_anim = o_attachevent_fp.createobjs().anim;

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

		a_prod = moxieHash.productGallery.a_allprod[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( "moxifier" ); }
	}

	if( $_("a-fun-game-moxiematch") ){
	        $_("a-fun-game-moxiematch").onclick = function(){ accessGame("moxiematch"); }
	}

	if( $_("a-fun-game-moxifier") ){
	        $_("a-fun-game-moxifier").onclick = function(){ accessGame("moxifier"); }
	}
	
	if( $_("a-fun-game-moxiemixer") ){
	        $_("a-fun-game-moxiemixer").onclick = function(){ accessGame("moxiemixer"); }
	}	

	if( $_("a-home-promo-secret") ){
		$_("a-home-promo-secret").onclick = function(){ dropCookieSecretCode(); } 
	}

	if( $_("a-fun-game-moxiesalon") ){
		$_("a-fun-game-moxiesalon").onclick = function(){ accessGame("moxiesalon"); }
	}

	if( $_("a-fun-game-beauty") ){
		$_("a-fun-game-beauty").onclick = function(){ accessGame("beauty"); }
	}

	if( $_("a-fun-game-weathergirl") ){
		$_("a-fun-game-weathergirl").onclick = function(){ downloadGame( ); } 
	}

	/* fun page events */
	if( $_("a-fun-secret-1") ){
		$_("a-fun-secret-1").onclick = function(){ secretscreen( o_attachevent_fp , 21 ); } 
	}

	if( $_("a-fun-secret-2") ){
		$_("a-fun-secret-2").onclick = function(){ secretscreen( o_attachevent_fp , 20 ); } 
	}

	/* homepage promos  */ 
	if( $_("div-home-promo1-en-us") ){
		$_("div-home-promo2-en-us").onclick = function(){ secretscreen( o_attachevent_fp , 21 );  } 
	}

	if( $_("div-home-promo2-en-us") ){
		$_("div-home-promo3-en-us").onclick = function(){ secretscreen( o_attachevent_fp , 20 ); } 
	}

}


function secretPromo( id ){
		o_main = new main("o_main");
	        o_attachevent_fp =   o_main.o_construct();
		secretscreen( o_attachevent_fp , id );
}


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

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    {
    c_start=c_start + c_name.length+1;
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    }
  }
return "";
}


function deleteCookie( name ){
	var expdate = new Date();
	expdate.setTime(expdate.getTime() - 1);
	return	document.cookie = name += "=; expires=" + expdate.toGMTString();
}


function videoEvent( ){
var flashvars = {}
var params = {wmode: "transparent"}
var attributes = {wmode : "transparent"}

for (var spots=1;spots<=3;spots++){
	 if( $_("div-home-promo" + spots + "-" + language) ){
		swfobject.embedSWF("smarty_files/templates/flash/home_promo" + spots + "_" + language + ".swf", "div-home-promo" + spots + "-" + language, "216" , "216" , "9.0.0" , "" , flashvars, params, attributes );
	 }
}
	 
    if( $_("div-logo") ){
		swfobject.embedSWF( "smarty_files/templates/flash/logo.swf" , "div-logo" , "216" , "216" , "9.0.0" , "" , flashvars , params , attributes );

    }	
	 
    if( $_("div-main-logo") ){
		swfobject.embedSWF( "smarty_files/templates/flash/logo_homepage.swf" , "div-main-logo" , "216" , "216" , "9.0.0" , "" , flashvars , params , attributes );
    }	 


    if( $_("div-volume") ){
		/* see if off exists */
		if(getCookie("volOff")){
			var flashvars={"playState":0}
		} else { 
			var flashvars={"playState":1}
		}
		swfobject.embedSWF( "smarty_files/templates/flash/volume.swf" , "div-volume" , "55" , "20" , "9.0.0" , "", flashvars , params , attributes );
    }
}

function setMuteCookie(){
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+50);
	document.cookie="volOff=1;expires="+exdate.toGMTString() + ";";
}

function removeMuteCookie(){
	var exdate=new Date();
	exdate.setDate(exdate.getDate()-50);
	document.cookie="volOff=1;expires="+exdate.toGMTString() + ";" + ";";
}

var videoplayEvent = function (){ 
        for (var i=0; i < moxieHash.video.length; i++ ){
                if( $_("a-video-" + moxieHash.video[i].element) ){
                        bindVideo( $_("a-video-" + moxieHash.video[i].element),i );
                }
        }
}

var bindVideo = function(obj,i){
        obj.onclick = function(){
                playVideo(moxieHash.video[i].path);
        }
}

function jcarousel(){
	if ( $("#mycarousel") ){
		$("#mycarousel-games,#mycarousel-fun, #mycarousel-ss").jcarousel( {
			itemLoadCallback: itemLoadCallbackFunction
		} );	
	}
}

function itemLoadCallbackFunction(carousel, state)
{
    for (var i = carousel.first; i <= carousel.last; i++) {
        // Check if the item already exists
        if (!carousel.has(i)) {
            // Add the item
            carousel.add(i, "I'm item #" + i);
        }
    }
}

function playVideo( uri ){
        var flashvars = { 
                file:uri,
                dock:'false', 
                autostart:'true'
        };
        var params = { 
                allowscriptaccess:'always',
                allowfullscreen:'true',
                WMODE:'transparent'
                };
        var attributes = {}; 
        swfobject.embedSWF("smarty_files/templates/flash/player.swf" , "div-video-content" , "394" , "394" , "9.0.0", "", flashvars, params, attributes);
}

function linkEvents(){
	if( $_("privacy") ){
	  	$_("privacy").onclick = function(){
			windowOpen( "http://www.mgae.com/privacy.asp"  , "500" , "500" );	
		}
	}
	if( $_("terms" ) ){
		$_("terms").onclick = function(){
			windowOpen( "http://www.mgae.com/terms.asp" , "500" , "500" );
		}
	}
}

function subcategoryEvent( o_acctutil ){
	if( $_("div-subcategory-dolls") ){ 
		$( ".a-subcategory" ).click( function(){ 
			var moxiecategory = moxieHash.productGallery.a_allprod[ this.id.substr(6) ];
				o_gallery = new galleryObj(o_anim, 'o_gallery', moxiecategory , IMG_PRELDR,DEF_PUBPATH + s_langcode + '/' + DEF_INTRFCELANGPATH);
				o_gallery.doImgPreload();
				$_('a-sub-avery').style.display='block';
				if($_('a-sub-bria')){
					$_('a-sub-bria').style.display='block';
				}
				$_('a-sub-lexa').style.display='block';
				if($_('a-sub-sasha')){
					$_('a-sub-sasha').style.display='block';
				}
				$_('a-sub-sophina').style.display='block';
				$_('a-sub-dolls').style.display='block';
				$_(this.id).style.display='none';
		});
	}
}


function wishlistEvent( o_acctutil ){
	if( $_("div-wishlist-wrapper") ){ 

			$("#wishlist-add").click( function(){
				var arrC = new Array();
				var arr =  $_("img-gallery").src.split("/");
				var newArr =  array_push( arr[ arr.length - 1 ] , arrC );
				alert( newArr );
				
			});
	}	
}


function frontgallery( ){

var flashvars = {}
var params = {wmode: "transparent"}
var attributes = {wmode : "transparent"}

	if( $_("div-flash-rotator") ){ 

		swfobject.embedSWF( "smarty_files/templates/flash/la_m2m_transition.swf" , "div-flash-rotator" , "653" , "251" , "9.0.0" , "" , flashvars , params , attributes );
	}	

}

function logoutEvent(){
	if( $_("a-logout") ){
		$("#a-logout").click( function(){
			$.post( "?request=logout" , { } , function( http ){ 
				window.location = "";	
			});
		 });
	}
}

function array_push( value , arr  ) {
		if( arr.length > 0 ){

			for( var i = 0; i <= arr.length; i++ ){
				if( arr[i] !== value ){ 
					arr[i] = value;
				}
			}
		}

		else { arr[i] = value; }

	return arr;
}


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( o_acctutil ) { 
/* 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 dialogBox(){
/* this object insert the dialog box to div-ctrldialog wich is the menu login/registeration */
	if( $_("div-ctrldialog") ){
    	 	$_("div-ctrldialog").style.display = "block";
     		$_("div-ctrldialog").innerHTML = "<div id=\"div-closebutton\"><a onclick=\"o_acctutil.doCloseCtrl();\" href=\"#\">[" + moxieHash.language.global["label-close"] + "]</a></div>";    
     		$_("div-ctrldialog").innerHTML += "<h4>" + moxieHash.language.registration["overlay-mess"] + "</h4>";
     		$_("div-ctrldialog").innerHTML += "<button id=\"login-btn\">" + moxieHash.language.homepage.login + "</button>";
     		$_("div-ctrldialog").innerHTML += "<button id=\"register-btn\">" + moxieHash.language.homepage.register + "</button>";
	}

}

function dropCookieSecretCode(){

	if( !obj.id ){
		document.cookie="secretCodeEnable=true; ;";
		dialogBox();
		o_main.o_construct();
	}
	else{
			accessGame("beauty");
	}

}


function checkSecretCookieEnable(){
		if( getCookie( "secretCodeEnable" ) && getCookie("finish") ){ 
			accessGame("beauty");
			deleteCookie( "secretCodeEnable" );
			deleteCookie( "finish" );
		}	
}


function accessGame( s_secretgame ){
	var b_loggin = ( obj.id )? true : false;	
	
		if( b_loggin ){
			if( moxieHash.secretGame[s_secretgame][2] ){
				var p_code = window.prompt( "Please enter the secret code" );    
                        	if( p_code == moxieHash.secretGame[s_secretgame][0] ){ 
					/* open the new window with uri */ 
					windowOpen( moxieHash.secretGame[s_secretgame][1] , moxieHash.secretGame[s_secretgame][3] , moxieHash.secretGame[s_secretgame][4] );
				 }
                       		else if( p_code == null ){    /* this means they cancelled the window */ }    
                        	else { /* */ accessGame( s_secretgame ); }
			}
			
			else{
				windowOpen( moxieHash.secretGame[s_secretgame][1] , moxieHash.secretGame[s_secretgame][3] , moxieHash.secretGame[s_secretgame][4] );
			}
		}
		
		else{ dialogBox(); o_main.o_construct(); }
} 

function downloadGame(){
	var b_loggin = ( obj.id )? true : false;	
		
	if( b_loggin ){
		windowOpen( "smarty_files/templates/MoxieWeatherGirl/index.php?appName=" + s_appName , 217 , 180  );
	}
	else{ dialogBox(); o_main.o_construct(); }
	
}

function secretscreen( o_attachevent_fp , id ){
	var b_loggin = ( obj.id )? true : false;	
		
	if( b_loggin ){
		var p_code = window.prompt("Please enter the secret code.");
		if( p_code.toUpperCase() == "MOXIESCREEN" ){ 
			o_attachevent_fp.createobjs().util.doDownloadWindow("?request=download&id=" + id );
		}
		else if( p_code == null ){ } 
		else { secretscreen( o_attachevent_fp ); }
 
	}
	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 );
}


var s_bio_girl = "lexa";

function doClickBioGirl(s_new_bio_girl){
	$_("div-bio-box").style.background = "url('smarty_files/templates/images/bio_box_"+ s_new_bio_girl + ".png') no-repeat top left";
	s_bio_girl = s_new_bio_girl;
	$_("div-bio-text").innerHTML=moxieHash.girls[s_new_bio_girl].bio;
	return false;
}

