// JavaScript Document
Event.observe(window, 'load', initializeInterface, false);
Event.observe(window, 'load', loadAccordions, false);

//****************************************MENU
//****************************************
function initializeInterface(){		
	//creo los picker de colores
	new Control.ColorPicker('backColor', {onUpdate: $('backColor').onchange});
	new Control.ColorPicker("color_content", {onUpdate: $('color_content').onchange});
	new Control.ColorPicker("color_title", {onUpdate: $('color_title').onchange});
	new Control.ColorPicker("color_links", {onUpdate: $('color_links').onchange});
	new Control.ColorPicker("borderColor_boxes", {onUpdate: $('borderColor_boxes').onchange});
	new Control.ColorPicker("backColor_boxes", {onUpdate: $('backColor_boxes').onchange});
	
	switch(appType){
		case 1:{
			new Control.ColorPicker("backColor_center", {onUpdate: $('backColor_center').onchange});
			new Control.ColorPicker("borderColor_center", {onUpdate: $('borderColor_center').onchange});
			new Control.ColorPicker("borderColor_boxes2", {onUpdate: $('borderColor_boxes2').onchange});
			new Control.ColorPicker("headerColor", {onUpdate: $('headerColor').onchange});
			break;}
		case 2:{
			new Control.ColorPicker("backColor_center", {onUpdate: $('backColor_center').onchange});
			new Control.ColorPicker("borderColor_center", {onUpdate: $('borderColor_center').onchange});
			break;}
		case 3:{
			new Control.ColorPicker("headersColor_center", {onUpdate: $('headersColor_center').onchange});
			new Control.ColorPicker("btnColor_center", {onUpdate: $('btnColor_center').onchange});
			new Control.ColorPicker("btnOverColor_center", {onUpdate: $('btnOverColor_center').onchange});
			break;}
	}
	//inicializo los tabs
	viewInTab(1,'backgroundImages_page');
	viewInTab(2,'fontTitle');
	viewInTab(0,'allThemes');
	if(appType==1){		
		viewInTab(3,'bordesCss_boxes');
		viewInTab(4,'backboxes');
		viewInTab(5,'topImage_page');
	}
	
	if(appType!=3){
		//configuro el slider de transparencia
		var el = document.getElementById("transparentia");
		el.onDragStart = function() {
			in_elem = document.getElementById('transparentiain').className = "move2ondrag";
			in_elem = document.getElementById('transparentia').className = "sliderondrag";
		}
		el.onDrag = function() {
			var value_elem = document.getElementById('transparentia_value');	
		};
		el.onDragStop = function() {
			in_elem = document.getElementById('transparentiain').className = "move2";
			in_elem = document.getElementById('transparentia').className = "slider";
			valor=Math.round(Number(this.value));
			if(valor>0)
				$('moreTransparency').value= 100-(valor/2);
			else
				$('moreTransparency').value= 0;
			myLayout.updateStyle();
		}
		form_slider(el, '100');
	}
	if(appType==1){
		//configuro el slider del spacio superior
		var el = document.getElementById("spacerHeader");
		el.onDragStart = function() {
			in_elem = document.getElementById('spacerHeaderin').className = "move2ondrag";
			in_elem = document.getElementById('spacerHeader').className = "sliderondrag";
		}
		el.onDrag = function() {
			var value_elem = document.getElementById('spacerHeader_value');	
		};
		el.onDragStop = function() {
			in_elem = document.getElementById('spacerHeaderin').className = "move2";
			in_elem = document.getElementById('spacerHeader').className = "slider";
			valor=Math.round(Number(this.value));
			if(valor>0)
				$('moreSpacerHeader').value= valor*2;
			else
				$('moreSpacerHeader').value= 0;
			myLayout.updateStyle();
		}
		form_slider(el, '250');
	}
	
	//configuro el drag de los paneles
	new Draggable('panelThemesOpts',{revert:false,handle: 'topThemesOpts', starteffect:false,reverteffect:false,endeffect:false});
	new Draggable('panelPagesOpts',{revert:false,handle: 'topPagesOpts', starteffect:false,reverteffect:false,endeffect:false});
	new Draggable('panelBoxesOpts',{revert:false,handle: 'topBoxesOpts', starteffect:false,reverteffect:false,endeffect:false});
	new Draggable('panelUpdateOpts',{revert:false,handle: 'topUpdateOpts', starteffect:false,reverteffect:false,endeffect:false});
	if(appType==1){
		new Draggable('panelTopImageOpts',{revert:false,handle: 'topTopImageOpts', starteffect:false,reverteffect:false,endeffect:false});
	}
	
	new Control.Modal('btnSupport',{
		iframe: true,
		width: 750,
		height: 550,
		overlayCloseOnClick:false
	});
	
	$('wait').hide();
}

//****************************************MENU
//****************************************
function myCallBackOnFinishUp(obj){
	  $('btnFormDown').show();
	  $('btnFormUp').hide();
}

function myCallBackOnFinishDown(obj){
 	  $('btnFormDown').hide();
	  $('btnFormUp').show();
}

function formUp(){
	if(opened!=""){
		new Effect.BlindUp($("panel" + opened + "Opts"));
		$('btn'+opened).removeClassName('btn'+opened+'Sel');
		opened="";
		}
	new Effect.SlideUp($('back_menu'),{afterFinish:myCallBackOnFinishUp});
	new Effect.Appear($('back_customize'));
	id=setInterval('Effect.Pulsate(\'btnCustomize\')',15000);
}

function formDown(){
	new Effect.Fade($('back_customize'));
	clearInterval(id);	
	new Effect.SlideDown($('back_menu'),{afterFinish:myCallBackOnFinishDown});	
}
	
//****************************************ACCORDION 
//****************************************
var themesAccordion;
var pageAccordion;
var boxesAccordion;
var updateAccordion;
var topImageAccordion;
var opened="";	
var tabOpened= new Array("","","","","","");
var numRandom;
var loadThemes=true;
var loadUserLayouts=true;
var loadRecents=true;
var loadBacks=true;
var loadTopImg=true;
var loadBacksContact=true;
var loadBacksExtended=true;
//variables para las cookies del background
varBacks=Array('backImageCategory','searchBackKeyword','image_keywords','backImageUrl','backImageNone','backFixed','backPosition','backRepeat','backColor','backImageCategoryId','themeId','themeName','profileId','profileName','profileType');



function loadAccordions() {
	themesAccordion = new accordion('panelThemesOpts', {
		classNames : {
			toggle : 'titleSection',
			toggleActive : 'titleSection_active',
			content : 'contentSection'
		},
		defaultSize : {
			width : 351
		}
	});	
	
	  pagesAccordion = new accordion('panelPagesOpts', {
		classNames : {
			toggle : 'titleSection2',
			toggleActive : 'titleSection_active2',
			content : 'contentSection2'
		},
		defaultSize : {
			width : 351
		}
	});
	
	  boxesAccordion = new accordion('panelBoxesOpts', {
		classNames : {
			toggle : 'titleSection3',
			toggleActive : 'titleSection_active3',
			content : 'contentSection3'
		},
		defaultSize : {
			width : 351
		}
	});
	
	 updateAccordion = new accordion('panelUpdateOpts', {
		classNames : {
			toggle : 'titleSection4',
			toggleActive : 'titleSection_active4',
			content : 'contentSection4'
		},
		defaultSize : {
			width : 351
		}
	});
	 
	if(appType==1){
			topImageAccordion = new accordion('panelTopImageOpts', {
			classNames : {
				toggle : 'titleSection5',
				toggleActive : 'titleSection_active5',
				content : 'contentSection5'
			},
			defaultSize : {
				width : 351
			}
		});
		topImageAccordion.activate($$('#panelTopImageOpts .titleSection5')[0]);
	}
		
	themesAccordion.activate($$('#panelThemesOpts .titleSection')[0]);
	pagesAccordion.activate($$('#panelPagesOpts .titleSection2')[0]);
	boxesAccordion.activate($$('#panelBoxesOpts .titleSection3')[0]);
	updateAccordion.activate($$('#panelUpdateOpts .titleSection4')[0]);	
}


//****************************************PANELS & TABS 
//****************************************
function showPanel(opt){
	if(opened!=opt){
		if(opened!=""){			
			new Effect.BlindUp($("panel" + opened + "Opts"));
			$('btn'+opened).removeClassName('btn'+opened+'Sel');			
		}
		if(opt=="Update")
			showVerify();
		opened=opt;
		new Effect.BlindDown($("panel" + opened + "Opts"),{afterFinish:myCallBackOnFinishShowPanel});
		$('btn'+opened).addClassName('btn'+opened+'Sel');
		//carga de thumbnails segun el itemn seleccionado
		switch(opened){
			case "Themes":{
				if(loadThemes){
					loadThumbThemes(-1,"",1);	
					loadThemes=false;
					}
				break;}
			case "Pages":{
				if(loadBacks){
					loadThumbImages(-1,-1,"Layouts",1)
					loadBacks=false;
					}
				break;}
			case "TopImage":{
				if(loadTopImg){
					loadThumbImages(-1,-1,"TopImage",1)
					loadTopImg=false;
					}
				break;}
		}
	}
}

function myCallBackOnFinishShowPanel(){
}

function viewInTab(navList, opt ){	
	if(tabOpened[navList]!=opt)
		if(tabOpened[navList]!=""){
			$('links'+ navList + "_" + tabOpened[navList]).removeClassName('tabSelected');
			$(tabOpened[navList]).hide();
			}
	tabOpened[navList]=opt;	
	$(tabOpened[navList]).show();
	$('links'+ navList + "_" + tabOpened[navList]).addClassName('tabSelected');

	//carga de thumbnails segun el itemn seleccionado
	switch(opt){
		case "userLayouts":{
			if(loadUserLayouts){
				loadThumbUserLayouts(appType,1);	
				loadUserLayouts=false;
				}
			break;}
		case "recentLayouts":{
			if(loadRecents){
				loadThumbUserLayouts(appType,0);	
				loadUserLayouts=false;
				}
			break;
			}
		case "backContactTb":{
			if(loadBacksContact){
				loadThumbImages(2685,-1,"Contact",1)
				loadBacksContact=false;
				}					
			break;}
		case "backExtended":{
			if(loadBacksExtended){
				loadThumbImages(2681,-1,"Extended",1)
				loadBacksExtended=false;
				}
			break;}
		case "uploadBackground_page":{
			$("errorUpload").innerHTML="&nbsp;";
			$("errorUpload").hide();
			$("upload_file").value="";
			break;}
		case "TopImage":{
			if(loadTopImg){
				loadThumbImages(-1,-1,"TopImage",1)
				loadTopImg=false;
			}
			break;}
	}

}

//******************************************BACKGROUND IMAGE UPLOAD
//******************************************
function checkUpload(){
	 $("errorUpload").innerHTML="&nbsp;";
	 $("errorUpload").hide();
	 if($("upload_file").value==""){
		  $("errorUpload").innerHTML="Must select a file";
		  $("errorUpload").show();
		 return false;
		 }
	fileType=extension($("upload_file").value);
	 if((fileType!=".gif")&&(fileType!=".jpg")&&(fileType!=".png")){
		  $("errorUpload").innerHTML="Only jpg, png or gif files";
		  $("errorUpload").show();
		 return false;
		 }
	 $('btnUpload').hide();
	 $('wait').show();
	 $("upload_form").submit();
}

function resUpload(resu){
	$('btnUpload').show();
	$('wait').hide();
	if(resu=="false"){
		$("errorUpload").innerHTML="Unknown error in upload";
		$("errorUpload").show();
		}
	else{
		$('backImageUrl').value=resu;
		$('backImage').value="body {background-image:url(" + $('backImageUrl').value + ");  ";
		$("backImageNone").checked=false;
		$('themeName').value="";
		$('backImageCategory').value="";
		$('backImageCategoryId').value="";
		$('searchBackKeyword').value="";
		myLayout.updateStyle();
	}
}

//******************************************BACKGROUND IMAGE UPLOAD
//******************************************
function checkUpload2(){
	 $("errorUpload2").innerHTML="&nbsp;";
	 $("errorUpload2").hide();
	 if($("upload_file2").value==""){
		  $("errorUpload2").innerHTML="Must select a file";
		  $("errorUpload2").show();
		 return false;
		 }
	fileType=extension($("upload_file2").value);
	 if((fileType!=".gif")&&(fileType!=".jpg")&&(fileType!=".png")){
		  $("errorUpload2").innerHTML="Only jpg, png or gif files";
		  $("errorUpload2").show();
		 return false;
		 }
	 $('btnUpload2').hide();
	 $('wait').show();
	 $("upload_form2").submit();
}

function resUpload2(resu){
	$('btnUpload2').show();
	$('wait').hide();
	if(resu=="false"){
		$("errorUpload2").innerHTML="Unknown error in upload";
		$("errorUpload2").show();
		}
	else{
		$('topImageUrl').value=resu;
		$("topImageNone").checked=false;
		myLayout.updateStyle();
	}
}

//******************************************UPDATE YOUR PROFILE
//******************************************
function verifyName(checkName){
	if((checkName==1)&&($('myName').value=="")){
		$('errorVerify').innerHTML="You must enter your Name";	
		$('myName').focus();
		return;
	}
	if((checkName==1)&&($('titleTag').value=="")){
		$('errorVerify').innerHTML="You must enter a title";	
		$('titleTag').focus();
		return;
	}
	if(checkName==0){
		$('myName').value="";
		$('titleTag').value="";
	}
		
	$('errorVerify').innerHTML="";
	
	if(appType==1)
		saveBordersImgs();
	else{
		saveData();	
		$("loadVerify").hide();
		}
}

function saveData(){
	//creamos el objeto
	 _obj_ajax=obj_ajax();
	 
	for(i=0,sep="",jsVars="";i<varNames.length;i++){
		//pregunto si es un checkbox (no encontre la funcion prototype que hace eso)
		if($(varNames[i]).value=="true"){
			if($(varNames[i]).checked)
				jsVars+=sep + varNames[i] + "=true";
			else
				jsVars+=sep + varNames[i] + "=false";
		}
		else
		 jsVars+=sep + varNames[i] + "=" + $(varNames[i]).value;
		
		sep="|";
	 }
	 //alert($("cssCode").value)
   _values_send="myName="+$("myName").value+"&titleTag="+$("titleTag").value+"&jsVars="+jsVars+"&cssCode="+$("cssCode").value+"&appType="+appType;  
   if($("profileType").value==appType)
		_values_send+="&profileId="+$("profileId").value;
 
	 _URL_="saveData.php?";
	 _obj_ajax.open("POST",_URL_,true); 
	 _obj_ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

	_obj_ajax.onreadystatechange=function() {                 
	 if (_obj_ajax.readyState==4) 
	 {
		if(_obj_ajax.status==200){						
				var userLayoutId=_obj_ajax.responseText;
				if (userLayoutId=='thumb_error')
				{
					alert('We are sorry, but your layout could not be saved ! Try again !');
				}
				else if (userLayoutId=='database_error')
				{
					alert('We are sorry, but your layout could not be saved ! Try again !');
				}
				else
				{
					updateUserLayout(userLayoutId);
					//getCode(userLayoutId);
					modalShow=new Control.Modal("linkShowCode",{
						iframe: true,
						width: 500,
						height: 400,
						loading: true,
						overlayCloseOnClick:false
						});
					modalShow.open();
					
					new Effect.BlindUp($("panel" + opened + "Opts"));
					$('btn'+opened).removeClassName('btn'+opened+'Sel');
					opened="";
				}
			 }
		}
	 }  
	_obj_ajax.send(_values_send); 
}

function getCode(userLayoutId){
	//creamos el objeto     
	 _obj_ajax=obj_ajax(); 
	 
	 _values_send="userLayoutId="+userLayoutId;  
	 _URL_="getCode.php?";     
	 _obj_ajax.open("POST",_URL_,true); 
	 _obj_ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

	_obj_ajax.onreadystatechange=function() {
	 if (_obj_ajax.readyState==4) {	
		if(_obj_ajax.status==200){
			modalShow=new Control.Modal("linkShowCode",{
				iframe: true,
				width: 500,
				height: 400,
				loading: true,
				overlayCloseOnClick:false
				});
			modalShow.open();
			
			new Effect.BlindUp($("panel" + opened + "Opts"));
			$('btn'+opened).removeClassName('btn'+opened+'Sel');
			opened="";			
			 }
		}
	 }  
	_obj_ajax.send(_values_send); 
}

function showVerify(){
	$('btnVerify').show();
	$('verifyUrl').show();
	$('manualInstall').hide();
	$('autoInstall').hide();
	}
	
function showManual(){
	$('verifyUrl').hide();
	$('autoInstall').hide();
	$('manualInstall').show();
	}

function showAuto()
{
	$('verifyUrl').hide();
	$('autoInstall').hide();
	$('manualInstall').show();
}

//****************************************THUBNAILS
//****************************************
function loadThumbImages(categoryId,sCategoryId,type,page){
	//creamos el objeto     
	 _obj_ajax=obj_ajax();   
	 
	 _values_send="categoryId=" + categoryId + "&sCategoryId=" + sCategoryId + "&page=" + page + "&type=" + type;  	 
	 _URL_="load_images.php?";   
	 _obj_ajax.open("GET",_URL_ + _values_send,true);   
	 
	 _obj_ajax.onreadystatechange=function() {                 
	if (_obj_ajax.readyState==4) {	
		if(_obj_ajax.status==200){   	
			  if (_obj_ajax.responseText!="false"){
			  	$("thumbs"+type).innerHTML=_obj_ajax.responseText;
				}
			else{
				error="loadThumbImages";
				}
			 }
		}
	 }  
 	_obj_ajax.send(null); 
	}

function loadThumbThemes(categoryId,txtSearch,page){
	//creamos el objeto     
	 _obj_ajax=obj_ajax();   
	 
	 _values_send="categoryId=" + categoryId + "&page=" + page + "&txtSearch=" + txtSearch;  	 
	 _URL_="load_themes.php?";   
	 _obj_ajax.open("GET",_URL_ + _values_send,true);   
	 
	 _obj_ajax.onreadystatechange=function() {                 
	if (_obj_ajax.readyState==4) {	
		if(_obj_ajax.status==200){   	
			  if (_obj_ajax.responseText!="false"){
			  	$("thumbsTheme").innerHTML=_obj_ajax.responseText;
				}
			else{
				error="loadThumbThemes";
				}
			 }
		}
	 }  
 	_obj_ajax.send(null); 
	}
	
function loadThumbUserLayouts(appType,page){
	//creamos el objeto     
	 _obj_ajax=obj_ajax();   
	 
	 _values_send="page=" + page + "&appType=" + appType;
	 _URL_="load_userlayouts.php?";   
	 _obj_ajax.open("GET",_URL_ + _values_send,true);   

	 _obj_ajax.onreadystatechange=function() {                 
	if (_obj_ajax.readyState==4) {	
		if(_obj_ajax.status==200){   	
			  if (_obj_ajax.responseText!="false"){
				  if(page==0)
				  	$("thumbsRecentLayouts").innerHTML=_obj_ajax.responseText;
				 else
				 	$("thumbsUserLayouts").innerHTML=_obj_ajax.responseText;
				}
			else{
				error="loadThumbUserLayouts";
				}
			 }
		}
	 }  
 	_obj_ajax.send(null); 
	}
	
function goSearchTheme(){
	loadThumbThemes(-1,document.getElementById("txtSearch").value,1)
}

//****************************************UPDATE THEME AND USER LAYOUTS
//****************************************
function startOver(){
	//para que lea las cookies si es necesario
	loadVars=paramLoadVars;
	
	if(opened!=""){
		new Effect.BlindUp($("panel" + opened + "Opts"));
		$('btn'+opened).removeClassName('btn'+opened+'Sel');
		opened="";
		}
	if($("load_themeId").value!="")
		updateTheme($("load_themeId").value);
	else
		if($("load_userLayoutId").value!="")
			updateUserLayout($("load_userLayoutId").value);
		else{
			initializeVars('');
			document.getElementById("previewFrame").src="profile_preview"+appSufix+".php";
			}
}

function startBlank(){
	if(opened!=""){
		new Effect.BlindUp($("panel" + opened + "Opts"));
		$('btn'+opened).removeClassName('btn'+opened+'Sel');
		opened="";
		}
	//para que no lea los cookies		
	loadVars='';
	//incializo todas las variables
	initializeVars('');
	document.getElementById("previewFrame").src="profile_preview"+appSufix+".php";
}

function updateTheme(id){	
	$('wait').show();
	//para que no lea los cookies		
	loadVars='';
	document.getElementById("previewFrame").src="profile_preview"+appSufix+".php?id="+id;
}	

function updateUserLayout(id){
	$('wait').show();
	document.getElementById("previewFrame").src="profile_preview"+appSufix+".php?userLayoutId="+id;
}

function changeEdit(opc){
	switch (opc){
		case 1:
			sufix="";break;
		case 2:
			sufix="_h";break;
		case 3:
			sufix="_f";break;
		case 4:
			sufix="_v2";break;
	}	

	/*
	for(i=0;i<varBacks.length;i++)
	{
		alert(varBacks[i]+' : '+$(varBacks[i]).value);
	}	
	*/

	//guardo las variables en cookies
	for(i=0;i<varBacks.length;i++){
		//pregunto si es un checkbox (no encontre la funcion prototype que hace eso)
		if($(varBacks[i]).value=="true"){			
			if($(varBacks[i]).checked)
				Cookie.set(varBacks[i],"istrue",1);
			else
				Cookie.set(varBacks[i],"isfalse",1);
		}
		else
			if((varBacks[i]!='profileName')&&(varBacks[i]!='profileType'))
				Cookie.set(varBacks[i],$(varBacks[i]).value,1);
			else{
				if(appType==$("profileType").value){
					Cookie.set(varBacks[i],$(varBacks[i]).value,1);
				}
			}
	 }	
	document.location.href="edit" + sufix + ".php?loadVars=true&titlekw="+$("titlekw").value;		
}

//****************************************************************************************************************
//ANTES MMYLAYOUT
//****************************************************************************************************************


//****************************************SETS & UPDATES CSS
//****************************************
function initializeVars(jsVars){
	if(jsVars==''){
		if(loadVars=="true"){
			//estas variables las incializo por las duda porque se agregaron cuando ya habia registros grabados
			$("backImageCategoryId").value='';
			
			//leo las variables de las cookies
			for(i=0;i<varBacks.length;i++){
				varValue=Cookie.get(varBacks[i]);
				if((varValue=="isfalse")||(varValue=="istrue"))
					$(varBacks[i]).checked=(varValue=="istrue")?1:0;
				else
					$(varBacks[i]).value=varValue;
			 }
			 if((appType==1)&&($("themeId").value!='')){
			 	updateTheme($("themeId").value);
			 }
		}
		else{ //valores por defecto
			$("backImageCategory").value='';
			$("searchBackKeyword").value='';
			$("image_keywords").value='';
			$("backImage").value='';
			$("backImageNone").checked=false;
			$("backFixed").checked=false;
			$("backPosition").value='top';
			$("backRepeat").value='repeat';
			$("backColor").value='E1E1E1';
			$("backImageCategoryId").value='';			
			if($("themeId").value=='')
				$("backImageUrl").value='';
		}
		$("backImage").value='';
		$("backColor_boxes").value='';
		$("borderColor_boxes").value='';
		setBorderCss('boxes','none');
		setBorderSize('boxes',1);		
		$("color_links").value='000000';
		$("color_content").value='000000';
		$("color_title").value='000000';
		setFontType('title','default','verdana')
		setFontSize('title','default','12px')
		setFontType('content','default','verdana');
		setFontSize('content','default','10px');
		setFontType('links','default','verdana');
		setFontSize('links','default','12px');			
		if(appType==1){
			$("contactBackImage").value='';
			$("contactBackImageNone").checked=false;
			$("contactBackImageNro").value='0';
			$("extendedBackImage").value='';
			$("extendedBackImageNone").checked=false;
			$("extendedBackImageNro").value='0';
			setBorderImg('center','none');
			$("borderColor_boxes2").value='';
			setBorderImg('boxes','none');
			$("moreHideExtendedNet").checked=false;
			$("moreHideContactTb").checked=false;
			$("headerColor").value='2358B8';
			$("moreSpacerHeader").value='0';
			newValue('0','spacerHeader');
		}		
		if(appType==2){
			setBorderCss('center','none');
			setBorderSize('center',1);
			$("backTransparent_center").checked=false;
			$("moreHideVanityBars").checked=false;
			$("moreHideDetails").checked=false;
		}
		if(appType==3){
			$("headersColor_center").value='E6F1F3';
			$("btnColor_center").value='D1E6E9';
			$("btnOverColor_center").value='17728F';
			$("backTransparent_boxes").checked=false;
			}
		if(appType!=3){
			$("backColor_center").value='FFFFFF';
			$("borderColor_center").value='';
			$("moreReverseProfile").checked=false;
			$("moreRemoveGeneral").checked=false;
			$("moreHideFriends").checked=false;
			if($("moreTransparency").value!=0){
				$("moreTransparency").value='0';
				newValue('0','transparentia');
			}
		}
	}
	else {//valores  de un userLayouts
		arrVars=jsVars.split("|");		
		for(i=0;i<arrVars.length;i++){
			auxValue=arrVars[i].split("=");			
			if((auxValue[1]=="false")||(auxValue[1]=="true")){
				for(j=0,sen=false;j<varNames.length;j++){
					if(varNames[j]==auxValue[0])
						sen=true;
				}
				if(sen)
					$(auxValue[0]).checked=(auxValue[1]=="true")?1:0;
				}
			else{				
				switch(appType){
					case 1:{
						switch(auxValue[0]){
							case 'borderImg_center':{setBorderImg('center',auxValue[1]);break;}
							case 'borderOpc_boxes':{setBorderCss('boxes',auxValue[1]);break;}
							case 'borderSize_boxes':{setBorderSize('boxes',auxValue[1]);break;}
							case 'borderImg_boxes':{setBorderImg('boxes',auxValue[1]);break;}
							case 'fontType_links':{setFontType('title','default',auxValue[1]);break;}
							case 'fontType_content':{setFontSize('title','default',auxValue[1]);break;}
							case 'fontType_title':{setFontType('content','default',auxValue[1]);break;}
							case 'fontSize_links':{setFontSize('content','default',auxValue[1]);break;}
							case 'fontSize_content':{setFontType('links','default',auxValue[1]);break;}
							case 'fontSize_title':{setFontSize('links','default',auxValue[1]);break;}
							default:{
								for(j=0,sen=false;j<varNames.length;j++){
								if(varNames[j]==auxValue[0])
									sen=true;
								}
								if(sen)
									$(auxValue[0]).value=auxValue[1];
								};
						}
						break;}
					case 2:{
						switch(auxValue[0]){
							case 'borderOpc_center':{setBorderCss('center',auxValue[1]);break;}
							case 'borderSize_center':{setBorderSize('center',auxValue[1]);break;}
							case 'borderOpc_boxes':{setBorderCss('boxes',auxValue[1]);break;}
							case 'borderSize_boxes':{setBorderSize('boxes',auxValue[1]);break;}
							case 'fontType_links':{setFontType('title','default',auxValue[1]);break;}
							case 'fontType_content':{setFontSize('title','default',auxValue[1]);break;}
							case 'fontType_title':{setFontType('content','default',auxValue[1]);break;}
							case 'fontSize_links':{setFontSize('content','default',auxValue[1]);break;}
							case 'fontSize_content':{setFontType('links','default',auxValue[1]);break;}
							case 'fontSize_title':{setFontSize('links','default',auxValue[1]);break;}
							default:$(auxValue[0]).value=auxValue[1];
						}
						break;}
					case 3:{
						switch(auxValue[0]){
							case 'borderOpc_boxes':{setBorderCss('boxes',auxValue[1]);break;}
							case 'borderSize_boxes':{setBorderSize('boxes',auxValue[1]);break;}
							case 'fontType_links':{setFontType('title','default',auxValue[1]);break;}
							case 'fontType_content':{setFontSize('title','default',auxValue[1]);break;}
							case 'fontType_title':{setFontType('content','default',auxValue[1]);break;}
							case 'fontSize_links':{setFontSize('content','default',auxValue[1]);break;}
							case 'fontSize_content':{setFontType('links','default',auxValue[1]);break;}
							case 'fontSize_title':{setFontSize('links','default',auxValue[1]);break;}
							default:$(auxValue[0]).value=auxValue[1];
						}
						break;}
					}
			}
		}			
		if(appType==1){
			$("moreSpacerHeader").value=$("moreSpacerHeader").value;
			newValue(($("moreSpacerHeader").value/2),'spacerHeader');
		}	
		if(appType==3){
			if($("moreTransparency").value!=0){
				$("moreTransparency").value='0';
				newValue('0','transparentia');
			}
		}

	}
	if((appType==$("profileType").value)&&($("profileName").value!="")){
			$("welcome").innerHTML='Welcome <span class="welcomeBig">'+$("profileName").value+'</span>';
	}
	myLayout.updateStyle();
}

function setBorderCss(element,value){
	document.getElementById("borderOpc_" + element + "_" + $('borderOpc_'+[element]).value).className="unselected";
	document.getElementById("borderOpc_" + element + "_" + value).className="selected";
	$('borderOpc_'+[element]).value=value;
	myLayout.updateStyle();
}

function setBorderSize(element,value){
	document.getElementById("borderSize_" + element + "_" + $('borderSize_'+[element]).value).className="unselected";
	document.getElementById("borderSize_" + element + "_" + value).className="selected";
	$('borderSize_'+[element]).value=value;
	myLayout.updateStyle();
}

function setBorderImg(element,value){
	document.getElementById("borderImg_" + element + "_" + $('borderImg_'+[element]).value).className="unselected";
	document.getElementById("borderImg_" + element + "_" + value).className="selected";
	$('borderImg_'+[element]).value=value;
	myLayout.updateStyle();
}

function setFontType(element,item,value){
	document.getElementById("fontType_" + element + "_" + $('fontTypeSel_'+[element]).value).className="unselected";
	document.getElementById("fontType_" + element + "_" + item).className="selected";
	$('fontType_'+[element]).value=value;
	$('fontTypeSel_'+[element]).value=item;
	myLayout.updateStyle();
}

function setFontSize(element,item,value){
	document.getElementById("fontSize_" + element + "_" + $('fontSizeSel_'+[element]).value).className="unselected";
	document.getElementById("fontSize_" + element + "_" + item).className="selected";
	$('fontSize_'+[element]).value=value;
	$('fontSizeSel_'+[element]).value=item;
	myLayout.updateStyle();
}

function updateLayoutsBackUrl(url,type){
	$('themeName').value="";
	$('backImageCategory').value="";
	$("backImageCategoryId").value="";
	if(type=="search")
		$('searchBackKeyword').value=$('image_keywords').value;
	else
		$('searchBackKeyword').value="";
	
	//creamos el objeto     
	 _obj_ajax=obj_ajax();   
	 
	 _values_send="url=" + url;  	 
 	 _URL_="imgbackground_copyurl.php?";    	    
	 _obj_ajax.open("GET",_URL_ + _values_send,true);   
	 
	 $("wait").show();
	 _obj_ajax.onreadystatechange=function() {              
	if (_obj_ajax.readyState==4) {
		if(_obj_ajax.status==200){	
			  if (_obj_ajax.responseText!="false"){
				$('backImageUrl').value=_obj_ajax.responseText;
				$('backImage').value="body {background-image:url(" + $('backImageUrl').value + ");  ";
				$("backImageNone").checked=false;
				myLayout.updateStyle();
				 $("wait").hide();
				}
			else{
				error="updateLayoutsBackUrl";
				}
			}
		}
	}  
 	_obj_ajax.send(null); 
}

function updateTopImagesBackUrl(url,type){
	//creamos el objeto     
	 _obj_ajax=obj_ajax();   
	 
	 _values_send="url=" + url;  	 
 	 _URL_="imgbackground_copyurl.php?";    	    
	 _obj_ajax.open("GET",_URL_ + _values_send,true);   
	 
	 $("wait").show();
	 _obj_ajax.onreadystatechange=function() {              
	if (_obj_ajax.readyState==4) {
		if(_obj_ajax.status==200){	
			  if (_obj_ajax.responseText!="false"){
				$("topImageUrl").value=_obj_ajax.responseText;
				$("topImageNone").checked=false;
				myLayout.updateStyle();
				 $("wait").hide();
				}
			else{
				error="updateTopImagesBackUrl";
				}
			}
		}
	}  
 	_obj_ajax.send(null); 
}

function updateLayoutsBackImg(nro,name,categoryId){
	if (nro!=0){
		path="http://www.myprofilepimp.us/myprofilepimp/public_html/presentation/images/personality-thumbnails/"+nro+".jpg";
		$('themeName').value="";
		$('backImageCategory').value=name;
		$('backImageCategoryId').value=categoryId;
		$('searchBackKeyword').value="";
		$('backImageUrl').value=path;
		$("backImageNone").checked=false;
		myLayout.updateStyle();
	}
}

function updateTopImageBackImg(nro,name,categoryId){
	if (nro!=0){
		path="http://www.myprofilepimp.us/myprofilepimp/public_html/presentation/images/personality-thumbnails/"+nro+".jpg";
		$('topImageUrl').value=path;
		$("topImageNone").checked=false;
		myLayout.updateStyle();
	}
}

function updateContactBackImg(nro){
	//si se paso un nro o no esta tildado el checkbox de ocultar la imagen debo mostrarla
	if ((nro!=0)||(!document.getElementById("contactBackImageNone").checked)){
		//sino vino un nro, me fijo si tenia uno de antes
		if(nro==0)
			nro=$('contactBackImageNro').value;
		//si existe alguna imagen genero el codigo
		if(nro!=0){
			path_cnt="http://www.myprofilepimp.us/myprofilepimp/public_html/presentation/images/personality-thumbnails/"+nro+".jpg";	
			_value="table.contactTable {width:292px !important; height:166px !important;background-image:url(" + path_cnt + ");background-repeat: no-repeat; background-color:transparent; background-attachment:scroll; background-position:center center; padding:0px !important;} ";
			_value+=".contactTable table, table.contactTable td {background-color:transparent;  background-image:none;  padding:0px !important;} ";
			_value+=".contactTable a {display:block; height:28px; width:115px;} .r{} .contactTable a img {filter:alpha(opacity=0); opacity:0; border:0px !important;} ";
			_value+=".contactTable .text {font-size:1px !important;} ";
			$('contactBackImage').value=_value;
			$('contactBackImageNro').value=nro;
			$("contactBackImageNone").checked=false;
			}
		}
	else
		//oculto la imagen
		$('contactBackImage').value="";
	myLayout.updateStyle();
}

function updateExtendedBackImg(nro){
	//si se paso un nro o no esta tildado el checkbox de ocultar la imagen debo mostrarla
	if ((nro!=0)||(!document.getElementById("extendedBackImageNone").checked)){
		//sino vino un nro, me fijo si tenia uno de antes
		if(nro==0)
			nro=$('extendedBackImageNro').value;
		//si existe alguna imagen genero el codigo
		if(nro!=0){
			path_ntw="http://www.myprofilepimp.us/myprofilepimp/public_html/presentation/images/personality-thumbnails/"+nro+".jpg";
			_value='span.blacktext12 {width: 435px;  height: 74px;background-image:url(' + path_ntw + ');background-repeat: no-repeat; !important; display:block}';
			_value+='span.blacktext12 span {display:none} ';
			$('extendedBackImage').value=_value;
			$('extendedBackImageNro').value=nro;
			$("extendedBackImageNone").checked=false;
			}
		}
	else{
		if(document.getElementById("extendedBackImageNone").checked){
			//oculto la imagen
			$('extendedBackImage').value="";
			}
		}
	myLayout.updateStyle();
}


function saveBordersImgs(){
	//parche para uso local y debug
	if(appPath=="http://localhost/myflyprofile"){
		myLayout.updateStyle();
		saveData();	
		$("loadVerify").hide();
	}
	else{
		if(($("borderImg_center").value!="none")||($("borderImg_boxes").value!="none")){
			numRandom = aleatorio(10000,99999) ;
			//genero la nueva imagen
			_obj_ajax=obj_ajax(); 
			//reviso valor por defecto center style
			color2_center="000000";
			if($("borderColor_center").value!='')
				color2_center=$("borderColor_center").value;
			
			//reviso valores por defecto boxes
			opcSel_boxes=0;
			color1_boxes="666666";
			color2_boxes="000000";				
			if($("borderImg_boxes").value!="none")
				opcSel_boxes=$("borderImg_boxes").value;
			if($("backColor_boxes").value!='')
				color1_boxes=$("backColor_boxes").value;	
			if($("borderColor_boxes2").value!='')
				color2_boxes=$("borderColor_boxes2").value;
				
			_values_send='sessionId=' + sessionId + '&numRandom=' + numRandom + '&color1_center=' + $("backColor_center").value + '&color2_center=' + color2_center + '&opcSel_center=' + $("borderImg_center").value + '&color1_boxes=' + color1_boxes + '&color2_boxes=' + color2_boxes + '&opcSel_boxes=' + opcSel_boxes;
			 $("errorVerify").innerHTML="";
			 $("errorVerify").hide();
			 $('btnVerify').hide();
			 $("loadVerify").show();
			 
			_URL_="includes/borders_generator.php?";   
			_obj_ajax.open("GET",_URL_ + _values_send,true);   
			_obj_ajax.onreadystatechange=function() {                 
			if (_obj_ajax.readyState==4) {	
				if(_obj_ajax.status==200){   	
					if (_obj_ajax.responseText!="false"){	
						myLayout.updateStyle();
						saveData();	
						$("loadVerify").hide();
						}
					else{
						error="borders_generator";
						}
					 }
				}
			}  
			_obj_ajax.send(null); 
		  }
		else{
			myLayout.updateStyle();
			saveData();	
			$("loadVerify").hide();
		}
	}
}

var Layout = Class.create();
Layout.prototype = {
 initialize: function(css_selectors, options) {
	 
    this.insertionID = options.insertionID;
    this.frame = $(options.frame);
    this.css_selectors = $H(css_selectors);
    window.onresize = this.onResize.bind(this);
    var self = this;
    this.css_selectors.each(function(keyVal) {
      var name = keyVal[0];
      var inputSrc, inputChange;
      if (keyVal[1].usage == 'boolean') {
        inputSrc = 'checked';
        inputChange = 'click';
     }
      else {
        inputSrc = 'value';
        inputChange = 'change';
     }
      $(name)['on'+inputChange] = function() {
        self.updateStyle(true);
     };
   });
 },
  _generateCSS: function() {
	 var cssCode="";
	 var marginHead="";
 	 var self = this;
	 
	//evaluo condiciones especiales
	
	//condiciones referentes al background
	this.updateLayoutBackImg();
	if(appType==1){
		this.updateTopImageBackImg();
		if (($('topImageUrl').value!="")&&($('topImageNone').checked==false)){
			if($('moreSpacerHeader').value==0){
				$('moreSpacerHeader').value=250;
				newValue('125','spacerHeader');
				}
			}
		else{
			if($('topImageNone').checked){
				$('moreSpacerHeader').value=0;
				newValue('0','spacerHeader');
			}
		}
	}
	
	if(appType==1){
		//Condiciones para el center style y los boxes
		if(($("borderImg_center").value!="none")||($("borderImg_boxes").value!="none")){
			img_center=img_328b=img_328t=img_435b=img_435t="";
			//parche para uso local y debug
			if(appPath=="http://localhost/myflyprofile"){
				img_center= appPath + '/images/edit/center/'+$("borderImg_center").value+'.png';
				img_328b= appPath + '/images/edit/boxes/'+$("borderImg_boxes").value+'_328b.png';
				img_328t= appPath + '/images/edit/boxes/'+$("borderImg_boxes").value+'_328t.png';
				img_435b= appPath + '/images/edit/boxes/'+$("borderImg_boxes").value+'_435b.png';
				img_435t= appPath + '/images/edit/boxes/'+$("borderImg_boxes").value+'_435t.png';
			}
			else{
				if(opened!="Update"){
					//controlo si debo poner el center style
					if($("borderImg_center").value!="none"){
						//genero la nueva imagen
						color1=$("backColor_center").value;
						color2=$("borderColor_center").value;
						if(color2=='')
							color2="000000";	
						img_center= appPath + '/includes/bordes.php?color1=' + color1 + '&color2=' + color2 + '&img=' + appPath + '/images/edit/center/' + $("borderImg_center").value + '.png';
					}
					//boxes
					opcSel=0;
					color1="666666";
					color2="000000";				
					if($("borderImg_boxes").value!="none")
						opcSel=$("borderImg_boxes").value;
					if($("backColor_boxes").value!='')
						color1=$("backColor_boxes").value;	
					if($("borderColor_boxes2").value!='')
						color2=$("borderColor_boxes2").value;
					img_328b= appPath + '/includes/bordes.php?color1=' + color1 + '&color2=' + color2 + '&img=' + appPath + '/images/edit/boxes/' + opcSel + '_328b.png';
					img_328t= appPath + '/includes/bordes.php?color1=' + color1 + '&color2=' + color2 + '&img=' + appPath + '/images/edit/boxes/' + opcSel + '_328t.png';
					img_435b= appPath + '/includes/bordes.php?color1=' + color1 + '&color2=' + color2 + '&img=' + appPath + '/images/edit/boxes/' + opcSel + '_435b.png';
					img_435t= appPath + '/includes/bordes.php?color1=' + color1 + '&color2=' + color2 + '&img=' + appPath + '/images/edit/boxes/' + opcSel + '_435t.png';
				}
			else{
				//controlo si debo poner el center style
				if($("borderImg_center").value!="none"){
					img_center= appPath + '/images/render_final/c' + $("borderImg_center").value + '_' + sessionId + numRandom + '.png';
				}
				opcSel=0;
				if($("borderImg_boxes").value!="none")
					opcSel=$("borderImg_boxes").value;
				//boxes
				img_328b= appPath + '/images/render_final/b328b' + opcSel + '_' + sessionId + numRandom + '.png';
				img_328t= appPath + '/images/render_final/b328t' + opcSel + '_' + sessionId + numRandom + '.png';
				img_435b= appPath + '/images/render_final/b435b' + opcSel + '_' + sessionId + numRandom + '.png';
				img_435t= appPath + '/images/render_final/b435t' + opcSel + '_' + sessionId + numRandom + '.png';
	
				}
			}
		
			cssCode+='.bodyContent table {border-collapse: separate; line-height: auto;} ';
			cssCode+='body * {line-height: 14px;} ';
			cssCode+='body{line-height: 1px;background-color: FFFFFF; color: 000000; background-repeat: no-repeat; background-position: top center;background-image: url("http://www.weebly.com/weebly/render/users/320266/307212425890884//bga.png");background-attachment: fixed;overflow-x: hidden; margin-top: 0px;} ';
			cssCode+='body table div {position: relative; padding-top: 50px; height: 220px; top: -220px; left: 4px; background-repeat: repeat-y;  background-position: top center;  background-image: url("' + img_center + '"); %%CENTERBG%%} ';
			cssCode+='body table div div {background-image: none; position: static; top: 0px; left: 0px; padding-top: 0px; height: auto;} ';
			cssCode+=' body table table div {background-image: none; position: static; top: 0px; left: 0px; padding-top: 0px; height: auto;}'; 
			cssCode+='body div table div {position: static; top: 0px; left: 0px; padding-top: 0px; height: auto;} ';
			cssCode+='p {margin: 0px 0px 1em 0px; color: 000000; !important}a, a:link, a:visited{color: 000000; text-decoration: none;}a:hover{color: 000000; text-decoration: none}img {border: none}br {line-height: 20px;}form{border-width:0px;background-color:none;}input {background-color:transparent !important}body>div {margin-left: 10px;}table, tr, td, table table, table table td {border-width:0px; background-color: transparent;}table table table td{background-color:transparent;margin:0px;padding: 0 26px 15px 26px}table table table table{border-width:0px;background-color:transparent;padding:0px;margin:0px; background-image: none;}table table table table td{padding:0px;margin:0px;}';
			cssCode+='table table table {margin:0px;background-color:' + $("backColor_boxes").value + ';width: 100% !important;border-width: 0px; border-style: solid; border-color: transparent;table-layout: auto;}';
			cssCode+='.friendsComments {table-layout: auto; height: auto;} ';
			cssCode+='.friendsComments table table {width: 435px; height: 300px;} ';
			cssCode+='.friendsComments table, .friendsComments tbody, .friendsComments tr, .friendsComments td {table-layout: auto;height: auto;}';
			cssCode+='body td table, body div table {margin-top: 0;}';
			cssCode+='.nametext {overflow: hidden;height: auto;width: 270px;text-align: left;color: 000000;padding: 0px 0px 3px 15px;display: block;margin: 14px 0px 0px 0px;border-width: 0px;}';
			cssCode+='.profileInfo table {padding: 0 0 10px 0;}';
			cssCode+='.profileInfo br {line-height: 0px;}';
			cssCode+='.profileInfo .nametext {padding-bottom: 0px !important;padding-bottom: 15px;} ';
			cssCode+='.profileInfo table td.text {padding: 0; margin: 0;} ';
			cssCode+='.profileInfo table td.text:last-child {padding-right: 5px;} ';
			cssCode+='.profileInfo table td {padding: 0; margin: 0; position: relative; left: 11px;}';
			cssCode+='.contactTable {width: 328px !important; background-color:' + $("backColor_boxes").value + '; height: 185px;} ';
			cssCode+='.contactTable table {margin-bottom: 10px;} ';
			cssCode+='.contactTable td {padding: 0px;	margin: 0px;		text-align: center;}';
			cssCode+='.contactTable td table {background-color: transparent;}';
			cssCode+='.contactTable a {padding: 0px;	margin: 0px 0px 1px 5px;	display: block;	height: 30px;	width: 136px;	background-color: transparent;}';
			cssCode+='table tr td table tr td table tr td div strong {display: block;	width: 270px;}';
			cssCode+='.blurbs span {display: none;}';
			cssCode+='.blurbs table span {display: block;}';
			cssCode+='.whitetext12{color: 000000; margin: 0px 0px 4px 0px; padding: 0px 0px 6px 15px; text-align: left; display: block; border-width: 0px 0px 0px 0px; border-style: double; border-color: d7c59f; width: 270px} ';
			cssCode+='.userProfileDetail .whitetext12 {padding: 0px 0px 6px 8px;} ';
			cssCode+='.blacktext12{color: 000000; display: block; margin-top: 14px;}';
			cssCode+='.btext{color: 000000;  margin: 14px 0px 4px 0px; padding: 0px 0px 3px 0px; display: block;text-align: left; border-width: 0px 0px 0px 0px; border-style: double; border-color: d7c59f}';
			cssCode+='.orangetext15{color: 000000; margin: 14px 0px 4px 0px; padding: 0px 0px 3px 0px; text-align: left; display: block; border-width: 0px 0px 0px 0px; border-style: double; border-color: d7c59f; width: 372px}';
			cssCode+='.friendSpace td.text table a.redlink {display: inline;} ';
			cssCode+='table tr td table tr td.text table tr td.text table tr td table tr td img {max-width: 225px !important; width: auto !important; width: 225px;} ';
			cssCode+='table tr td table tr td.text table tr td.text table tr td table tr td img.ImgOnlineNow {width: auto;} ';
			cssCode+='table tr td table tr td.text table tr td.text table tr td table tr td a img {width: 90px;} ';
			cssCode+='table table td.text table.friendSpace td.text a img {width: auto;} ';
			cssCode+='table tr td table tr td.text table tr td.text table tr td table tr td object, table tr td table tr td.text table tr td.text table tr td table tr td embed {max-width: 225px !important; max-height: 185px !important; width: auto !important; width: 225px; height: auto !important; height: 185px;} ';
			cssCode+='u {text-decoration: none;}';
			cssCode+='body * {background-repeat: repeat-y;  background-position: top center;  background-image: url("' + img_center + '"); %%CENTERBG%%}body * * {background-image: none;} ';
			cssCode+='body table td {padding: 0 7px 0 0px;} ';
			cssCode+='body table td.text {padding: 0 19px 0 4px;} ';
			cssCode+='body table table table td.text {padding: 0px;}'; 
			cssCode+='body table table td {position: relative; left: 13px;} ';
			cssCode+='body table table table td {position: static;} ';
			cssCode+='body table table td.text {position: static;} ';
			cssCode+='body table table table td {padding: 0;} ';
			cssCode+='table table table.latestBlogEntry {background-color: transparent; ' + $("backColor_boxes").value + ';} ';
			cssCode+='table table table table, table table table.friendSpace table span, table table table.friendsComments table span {background-color: E6E2AF;} ';
			cssCode+='table table table.friendSpace, table table table.blurbs table, table table table.userProfileURL table, table table table.friendSpace table, table table table.friendsComments table {background-color: transparent;} ';
			cssCode+='.userProfileDetail, .userProfileCompany, .profileInfo, .userProfileNetworking, .userProfileSchool, .interestsAndDetails {margin: 0px;  background-color: transparent; background-image: url("' + img_328t + '"); background-repeat: no-repeat; background-position: top left;  width: 100% !important;  color: 000000;  padding: 0px;  width: 328px !important;} ';
			cssCode+='.userProfileDetail table, .userProfileCompany table, .profileInfo table, .userProfileNetworking table, .userProfileSchool table, .interestsAndDetails table {background: transparent url("' + img_328b + '") no-repeat bottom left;  padding-bottom: 15px; padding-top: 10px;  width: 100%;}';
			cssCode+='.userProfileNetworking table td, .userProfileCompany table td {padding: 0 15px 10px 15px;}';
			cssCode+='.profileInfo table a img {margin-left: 15px;}';
			cssCode+='.profileInfo table a {line-height: 40px;}';
			cssCode+='.userProfileDetail table td, .userProfileCompany table td, .interestsAndDetails table td {position: relative; top: -10px; left: 0px; padding: 0 15px;}';
			cssCode+='.userProfileCompany table br {line-height: 15px;}';
			cssCode+='.userProfileCompany table {height: auto !important;  height: 75px;}';
			cssCode+='.userProfileDetail table {height: auto !important;  height: 195px;}';
			cssCode+='.userProfileURL {background: none;}';		
			cssCode+='.blurbs, .friendSpace, .friendsComments {padding: 0;  background: transparent url("' + img_435t + '") no-repeat top left;  overflow: hidden;  width: 435px;}';
			cssCode+='.blurbs td, .friendSpace td, .friendsComments td {background: transparent url("' + img_435b + '") no-repeat bottom left;  padding: 0 15px 15px 15px;}';
			if (($('extendedBackImageNro').value=='0')||($("extendedBackImageNone").checked)){
				cssCode+='.extendedNetwork {padding: 0;  background: transparent url("' + img_435t + '") no-repeat top left;  overflow: hidden;  width: 435px;}';
				cssCode+='.extendedNetwork td {background: transparent url("' + img_435b + '") no-repeat bottom left;  padding: 0 15px 15px 15px;}';
				cssCode+='span.blacktext12 {width: 435px;  height: 74px;}';
				}
			else{
				cssCode+='.extendedNetwork {padding: 0;  background: transparent url("") no-repeat top left;  overflow: hidden;  width: 435px;}';
				cssCode+='.extendedNetwork td {background: transparent url("") no-repeat bottom left;  padding: 0 15px 15px 15px;}';
				}
			cssCode+='.friendSpace td td, .friendsComments td td {background: none;  padding: 0;} ';
			cssCode+='body table table td.text table.friendSpace td, body table table td.text table.friendsComments td {padding: 0 15px 20px 15px;} ';
			cssCode+='body table table td.text table.friendSpace td td, body table table td.text table.friendsComments td td {padding: 0;} ';
			cssCode+='.extendedNetwork span {display: block;}';
			cssCode+='.latestBlogEntry {background-color: ' + $("backColor_boxes").value + ';}';
			cssCode+='.blurbs td td{background: transparent;}';
			cssCode+='.blurbs td.text {display: none;}';
			cssCode+='.blurbs table .text .orangetext15,.blurbs table .text span{display: inline;}';
			cssCode+='.blurbs table br {line-height: 0px;}';
			cssCode+='.blurbs table .text br {line-height: 20px;}';
			cssCode+='body table {margin-top: 0px;position: relative;padding: 0 1px 10px 1px;left: 5px;}body table table table {left: 0px;}';
			cssCode+='body table {position: relative;padding: 0 1px 10px 1px;left: 5px;}body table table table {left: 0px;}';
			cssCode+='.whitetext12{width: auto}';
			cssCode+='.contactTable {width: 100% !important; padding: 0px;}';
			cssCode+='.userProfileDetail, .userProfileCompany, .profileInfo, .userProfileNetworking, .userProfileSchool {width: 335px !important;}';
			cssCode+='.userProfileDetail table, .userProfileCompany table, .profileInfo table, .userProfileNetworking table, .userProfileSchool table, .interestsAndDetails table {padding: 0 15px 15px 15px;}';
			cssCode+='.profileInfo table a img {margin-left: 0;}';
			cssCode+='.profileInfo table a {line-height: 20px;}';
			cssCode+='.orangetext15 {width: auto;}';
			cssCode+='.nametext {height: 35px;width: auto;}';
			cssCode+='.masthead {top: 164; margin-left: -420px;} ';
			cssCode+='.mastbottom {bottom: 164; margin-left: -420px;} ';
			cssCode+='body table td {padding: 0 13px 0 0px;}body table td:first-child {padding: 0 0px 0 0px;}';
			cssCode+='.blurbs table tr td,.extendedNetwork table tr td, .friendSpace table tr td, .friendsComments table tr td {padding: 0 15px 15px 15px;}';
			cssCode+='.blurbs table tr td td,.extendedNetwork table tr td td, .friendSpace table tr td td, .friendsComments table tr td td {padding: 0 0px;}table table table td{padding: 0;} ';
			cssCode+='body table table td.text table {position: relative; left: -17px;} ';
			cssCode+='body table table td.text table table {position: static;} ';
			cssCode+='body table table {position: relative; left: 20px;} ';
			cssCode+='body table table table {position: static;} ';
			cssCode+='body table div {left: 0px;} ';
			cssCode+='body>table table td.text table.friendsComments td.text>table:last-child>tbody>tr:last-child a {display: block; text-align: left; margin-left: 320px;} ';
			cssCode+='table table table.latestBlogEntry {background-color: ' + $("backColor_boxes").value + ';} ';
			cssCode+='table table table table, table table table.friendSpace table span, table table table.friendsComments table span {background-color: transparent;}';
		}
		
		//opciones que afectan a los boxes
		if(($('backColor_boxes').value!='')||($('borderColor_boxes').value!='')||($('borderOpc_boxes').value!='none')||($('borderSize_boxes').value!='1')){
			cssCode+="table,tr,td{background-color: transparent;border-style: none;}  ";
			cssCode+="table table table{background-color: transparent;border-style: none;}  ";
			cssCode+="table table,table table table table,table table table td{background: transparent;border-style: none;} ";
			
			if(($("borderImg_boxes").value=="none")&&($("borderImg_center").value=="none")){
				if($("backColor_boxes").value!="")
					cssCode+="table table table{background-color: "+$("backColor_boxes").value+"} ";
				}
			if($("borderImg_boxes").value=="none"){
				if($("borderOpc_boxes").value!="none")
					cssCode+= "table table table{border-style: "+$("borderOpc_boxes").value+";}"
				if($("borderSize_boxes").value!="1")
					cssCode+="table table table{border-width:"+$("borderSize_boxes").value+"px !important;} "			
				if($("borderColor_boxes").value!="")
					cssCode+="table table table{border-color:"+$("borderColor_boxes").value+" !important;}";
				else
					if($("borderOpc_boxes").value!="none")
						cssCode+="table table table{border-color:000000 !important;}";
				}
		}
	}
	
	if(appType==2){
		//Coriijo bugs (hi5)
		cssCode='body{background-image:none;}#user-details{border:none;}';
	}
	
	
	this.css_selectors.each(function(keyVal) {
	 if($(keyVal[1]).default_val!=$(keyVal[0]).value){
      var rules = keyVal[1];
      if (rules.func) {
        cssCode += Layout.prototype[rules.func].call(self, keyVal[0].value);
     }
      else if (rules.usage == 'boolean') {
        if ($(keyVal[0]).checked) {
          cssCode += rules.css;
       }
     }
      else if (rules.usage == 'replace') {
        var selectorValue = $(keyVal[0]).value;
        if (rules[selectorValue] != null) {
          cssCode += rules[selectorValue];
       }
        else {
          cssCode += rules.css.gsub('@arg@', selectorValue);
       }
     }
	}
   });

	if(appType==1){
		linkTop="";
		if($('moreSpacerHeader').value!=0)
			linkTop='<a style="border:0;" href="http://www.myprofilepimp.com/myfly" title="!" class="myFlyBannerTop" target="_blank"><span></span></a>';

		imgTopLeft='<div style="width:120px; height:120px; position:absolute; top:0px; left:0px;"><a href="http://www.myprofilepimp.com/myfly" target="_blank"><img src="'+logotoppleft+'" style="border:none;"></a></div><a href="http://www.myprofilepimp.com/myfly"><img src="http://www.myflyprofile.myprofilepimp.com/images/site/logo.gif" height="50" /></a><br /><a href="http://www.myprofilepimp.com/myfly">Make your OWN Custom Layout @ MyFlyProfile.Net</a> | <a href="http://www.myprofilepimp.com/myfly">Pimped By MyFlyPrOFiLe.NeT</a><br><br><a href="//www.commentsheaven.com" target= "blank"><img src="http://www.myprofilepimp.us/myprofilepimp/public_html/presentation/images/commentsheaven.gif"></a>';
		
		imgTopRight='<a style="position:absolute;right:0px;top:0px;z-index:9999;" href="http://www.myprofilepimp.com/myfly" target="_blank"><img src="'+logotoppright+'" style="position:fixed;right:0px;top:0px" border="0"></a>';

		if(opened!="Update") //codigo del preview
			$('cssCode').value=$('cssTheme').value+"<style>"+marginHead+cssCode+'</style>';
		else //codigo final para copiar
			$('cssCode').value=$('cssTheme').value+"<style>"+marginHead+'</style><span style="display:none">MYFLYPROFILE.NET</span><style>'+cssCode+'</style>'+linkTop+imgTopLeft+imgTopRight;
		return marginHead+cssCode;
	}
	else{
		$('cssCode').value=cssCode;
		return cssCode;
	}
 },
  updateStyle: function(warnSafari) {
	if (/Konqueror|Safari|KHTML/.test(navigator.userAgent)) {
      if (warnSafari) {
        alert('On Safari browser, Step 3 options do not show up in this preview but will take place in your final layout.');
     }
   }
    else {
      var styleElt = this._getStyleElt();
      var cssText = this._generateCSS();
      if (styleElt.styleSheet) {
        styleElt.styleSheet.cssText = cssText;
     }
      else {
        styleElt.innerHTML = cssText;
     }
   }
	$('wait').hide();
 },
  updateLayoutBackImg: function(){
    var _value;
	_value="body {";	
	if ($('backImageUrl').value!="")
		_value+="background-image:url(" + $('backImageUrl').value + ");";
	_value+="background-position: "+ $('backPosition').value+" center;";
	_value+="background-repeat: "+ $('backRepeat').value+";";
	if($('backFixed').checked)
		_value+=" background-attachment:fixed;";
	_value+="} ";
	if($("backImageNone").checked){
		_value="body {background-image:none;} ";
		}
	$('backImage').value=_value;
	return _value;
 },
  onResize: function() {
    if (this.usingDiv) {this.updateBackgroundPosition();}
 },
  _getStyleElt: function() {
    return this._getPreviewElt(this.insertionID);
 },
  _getPreviewElt: function(id) {
    var frameDoc = this.frame.contentWindow.document;
    return frameDoc.getElementById(id);
 },
 updateTopImageBackImg: function(){
   var _value;
	_value=".myFlyBannerTop {";	
	if ($('topImageUrl').value!="")
		_value+="background-image:url(" + $('topImageUrl').value + ");";		
	_value+="background-position: top center; background-repeat: no-repeat;} ";
	
	if($("topImageNone").checked){
		_value=".myFlyBannerTop {background-image:none;} ";
	}
	$('topImage').value=_value;	
	return _value;	
 }
};

//****************************************OTHER FUNCTIONS & CLASSES
//****************************************
function Util() {
  throw new Error("Util is a static class. You can't create instances of it.");
}

Util.windowSize = function() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
 } else if( document.documentElement &&
    ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
 } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
 }
  return {width: myWidth, height: myHeight};
};

Util.createElement = function(doc,tagName) {
  var newElt = doc.createElement(tagName);
  if (typeof(newElt) != 'object') {newElt = doc.standardCreateElement(tagName);}
  return newElt;
};
  
/**
 * Given an HTMLElement, return the HTMLDocument it belongs to
 */
Util.getEltDoc = function(anElt) {
  if (anElt.ownerDocument) {return anElt.ownerDocument;}
  if (anElt.document) {return anElt.document;}
  return document;
};

/**
 * This method calls document.createElement() to create a new element, and 
 * then initialized the new element with the values provided by the caller.
 *
 * @scope    public class method
 * @param    tagName    The HTML tag for the element ("div", "p", "span", etc.). 
 * @param    cssClassName    Optional. The HTML/CSS class to assign to the new element. 
 * @param    attributesInJson    Optional. A JSON object with additional attributes to set on the new element. 
 * @param    text    Optional. A text string to put in a text node within the new element. 
 * @return   The newly created HTML element.
 */
Util.newElement = function(tagName, cssClassName, attributesInJson, text, style, doc) {

  if (!doc) {doc = document;}
  var newElement = Util.createElement(doc,tagName);
  if (cssClassName) {
    newElement.className = cssClassName;
 }
  if (attributesInJson) {
    for (var key in attributesInJson) {
      if (key == 'id') {
        newElement.id = attributesInJson[key];
     } else {
        if (key == 'jfor') {
          newElement.setAttribute('for', attributesInJson[key]);
       }
        else {
          newElement.setAttribute(key, attributesInJson[key]);
       }
     }
   }
 }
  if (style) {
      for (key in style) {
        if (key == 'cssFloat' && Util.isIE()) {
          newElement.style['styleFloat'] = style[key];
       }
        else {
          newElement.style[key] = style[key];
       }
     }
 }    
  if (text) {
    newElement.appendChild(doc.createTextNode(text));
 }
  return newElement;
};


/**
 * Given an HTML element, we first call document.createElement() to 
 * create a new element, and then call appendChild() to add the new 
 * element to the given element.
 *
 * Example:
 * <pre>
 * var menuUrl = "http://en.wikipedia.org/";
 * var menuText = "Wikipedia";
 * var menuItem = Util.appendNewElement(mainMenu, "li", NavbarView.CSS_CLASS_MENU_ITEM);
 * var link = Util.appendNewElement(menuItem, "a", null, {href: menuUrl}, menuText);
 * </pre>
 *
 * @scope    public class method
 * @param    parentElement    The existing element that we should append the new element to. 
 * @param    tagName    The HTML tag for the element ("div", "p", "span", etc.). 
 * @param    cssClassName    Optional. The HTML/CSS class to assign to the new element. 
 * @param    attributesInJson    Optional. A JSON object with additional attributes to set on the new element. 
 * @param    text    Optional. A text string to put in a text node within the new element. 
 * @return   The newly created HTML element.
 */
Util.appendNewElement = function(parentElement, tagName, cssClassName, attributesInJson, text,style) {
  var doc = Util.getEltDoc(parentElement);
  var newElement = Util.newElement(tagName, cssClassName, attributesInJson, text,style,doc);
  parentElement.appendChild(newElement);
  return newElement;
};


/**
 * Given an HTML element, we first call document.createTextNode() to 
 * create a new text node, and then call appendChild() to add the new 
 * text node to the given element.
 *
 * @scope    public class method
 * @param    parentElement    The existing element that we should append the new element to. 
 * @param    textString    The text string to put in the text node.
 * @return   The newly created text node.
 */
Util.appendNewTextNode = function(parentElement, textString) {

  var doc = Util.getEltDoc(parentElement);
  var newTextNode = doc.createTextNode(textString);
  parentElement.appendChild(newTextNode);
  return newTextNode;
};

Util.blankString = function(str) {
  return !(str && !str.match(/^\s*$/));
};

function appendScript(url) {
  var head = document.getElementsByTagName("head")[0];
  var script = document.createElement("script");
  script.charset = "utf-8";
  script.src = url;
  script.type = 'text/javascript';
  head.appendChild(script);
}

var ImagePicker = Class.create();
ImagePicker.prototype = {
  initialize: function(options) {
    options = Object.extend({
      selectedClass: 'selected',
      searchField: 'image_keywords',
      defaultEngine: 'yahoo'
   }, options || {});
    this.pickerDiv = $(options.pickerDiv);
    this.spinner = $(options.spinner);
    this.selectedClass = options.selectedClass;
    this.currentEngine = options.defaultEngine;
    this.searchField = $(options.searchField);
    this.setupEngineLinks();
   // $('image_preview').onclick = this.previewUrl.bindAsEventListener(this);
    //this.setupFreeLinks();
    //if (Prototype.Browser.WebKit) {$('upload_form').hide();}
 },
 /* setupFreeLinks: function() {
    var freeLinks = $$('#free_images a');
    var freeImages = $$('#free_images img');
    freeLinks.each(function(link, index) {
      var image = freeImages[Math.floor(index/2)];
      var fullSrc = image.src.sub('_thumb','');
      var imgInfo = new ImageInfo('free image',fullSrc);
      imgInfo.keywords = image.title;
      link.onclick = function() {le.setBackgroundForCheck(imgInfo);};
   });
 },*/
  setupEngineLinks: function() {
    var self = this;
    $H(ImageSearcher.engines).keys().each(function(engine) {
      self.setAnEngineLink(engine);
   });
 },
  setAnEngineLink: function(engineStr) {
    var elt = $('more_'+engineStr);
    var self = this;
    if (this.currentEngine == engineStr) {
      elt.onclick = null;
      Element.addClassName(elt, 'current');
   }
    else {

      elt.onclick = function() {self.selectNewEngine(engineStr, true);};
      Element.removeClassName(elt, 'current');
   }
 },
  selectNewEngine: function(engineStr, search) {
   if(engineStr!="photobucker"){
		document.getElementById("search_photobucker").style.display="none";
		document.getElementById("search_engines").style.display="block";
		if (engineStr != this.currentEngine) {	 
		  Element.removeClassName(this.searchField, this.currentEngine);
		  this.currentEngine = engineStr;
		  Element.addClassName(this.searchField, this.currentEngine);
		  this.setupEngineLinks();
		  if (search) {this.search();}
	   }
	}
 	else{
		document.getElementById("search_engines").style.display="none";
		document.getElementById("search_photobucker").style.display="block";
		Element.removeClassName(this.searchField, this.currentEngine);
		this.currentEngine = engineStr;
		Element.addClassName(this.searchField, this.currentEngine);
		this.setupEngineLinks();
	}
 },
    
  search: function(options) {
    options = Object.extend({
      engine: this.currentEngine,
      keywords: this.searchField.value
   }, options || {});

    Element.hide('more_image_results');
    Element.hide('previous_image_results');
    
    if (Util.blankString(options.keywords)) {return;}
    this.searchField.value = options.keywords;
    this.selectNewEngine(options.engine);
    Element.show(this.spinner);
    this.imageSearcher = new ImageSearcher(this, options);
 },
  
  update: function(images, options) {
    Element.hide(this.spinner);
    if (images.length > 0) {
      this.pickerDiv.innerHTML = '';
      var pickerDiv = this.pickerDiv;
      this.images = images;
      var self = this;
      images.each(function(imageInfo) {
        var thumbDiv = Util.appendNewElement(pickerDiv,'div','thumb');
        var link = Util.appendNewElement(thumbDiv,'a', null, {href:'javascript:void(0)'});
        var img = imageInfo.getThumbImage(96,96);
        imageInfo.keywords = options.keywords;
        img.onclick = function() {self.selectImage(this);};
        link.appendChild(img);
     });
      var moreLink = $('more_image_results');
      var newOptions = {keywords: options.keywords, page: options.page+1};
      moreLink.onclick = function() {self.search(newOptions);};
      Element.show('more_image_results');      
	  var backLink = $('previous_image_results');
	  var backOptions = {keywords: options.keywords, page: options.page-1};
	  backLink.onclick = function() {self.search(backOptions);};
	  if(options.page>1)
	      Element.show('previous_image_results');
	  else
	  	 Element.hide('previous_image_results');
   }
    else {
      this.pickerDiv.innerHTML = 'Sorry, no results found!';
   }
 },
  
  selectImage: function(image) {
    if (this.selectedImage == image) {return;}
    if (this.selectedImage && this.selectedImage.parentNode) {
      Element.removeClassName(this.selectedImage.parentNode, this.selectedClass);
   }
    if (image && image.parentNode) {
      Element.addClassName(image.parentNode, this.selectedClass);
   }
    this.selectedImage = image;
    $('backImageUrl').value = image.imgInfo.url;
	updateLayoutsBackUrl(image.imgInfo.url,"search");
    //le.setBackgroundForCheck(image.imgInfo);
 },
  previewUrl: function() {
    var imgInfo = new ImageInfo('submitted url',$('backImageUrl').value);
	//alert("2"+imgInfo);
    //le.setBackgroundForCheck(imgInfo);
 },
  updateErr: function(msg) {
    alert(msg);
 }
};

var ImageSearcher = Class.create();
ImageSearcher.engines = {
  yahoo: {
    baseURL: 'http://search.yahooapis.com/ImageSearchService/V1/imageSearch?appid=GArrmr_V34EaZ_IRTfXQlloNngp2Bd1K4KA3o5e5reuMT.Xbs8GTxyXS_kbDVQ--&output=json&results=8&callback=ImageSearcher.updateFunc&query=',
    updateFunc: function(results) {
      var images = [];
      results.ResultSet.Result.each(function(result) {
       // if (result.Width >= 300 && result.Height >= 225) {
          imgInfo = new ImageInfo(result.Title, result.Url, result.Thumbnail.Url,
             result.Width, result.Height, result.Thumbnail.Width, result.Thumbnail.Height);
          imgInfo.engine = 'Yahoo';
          imgInfo.creditsLink = result.RefererUrl;
          images.push(imgInfo);
        //}
     });
      this.picker.update(images, this.options);
   },
    pageParameter: function(page) {
      return 'start=' +((page-1)*8+1); // extra parens needed, otherwise will be casted as string
   }
 },
  flickr: {
   	baseURL: 'http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=0384128911b7cc5aab30e07584a307b9&per_page=8&sort=interestingness-desc&format=json&jsoncallback=ImageSearcher.updateFunc&license=4,5,6&text=',
    updateFunc:  function(results) {
      var errMsg = null;
        try {
          if (results.stat == 'ok') {
            var images = [];
            results.photos.photo.each(function(photo) {
              var imgUrl = 'http://farm' + photo.farm + 
                '.static.flickr.com/'+photo.server+'/'+photo.id+'_'+photo.secret+'.jpg';
              var thumbUrl = 'http://farm' + photo.farm + 
                '.static.flickr.com/'+photo.server+'/'+photo.id+'_'+photo.secret+'_s.jpg';
              var imgInfo = new ImageInfo(photo.title, imgUrl, thumbUrl, 1024, 768, 75, 75);
              imgInfo.engine = 'flickr';
              imgInfo.creditsLink = 'http://flickr.com/photos/' + photo.owner + '/' + photo.id;
              images.push(imgInfo);
           });
            this.picker.update(images, this.options);
         }
          else {
            errMsg = results.message;
         }
       }
        catch (e) {
          errMsg = e;
          throw e;
       }
        if (errMsg) {this.picker.updateErr(errMsg);}
   },
    pageParameter: function(page) {
      return 'page='+page;
   }
 },
  google: {
    baseURL: 'images/myflyproxy.php?keywords=',
    updateFunc: function(returnObj) {
      var images = [];
      returnObj.results.each(function(result) {
        //if (result.imageWidth >= 300 && result.imageHeight >= 225) {
          imgInfo = new ImageInfo(result.displayUrl, result.imageUrl, result.thumbnailUrl,
            result.imageWidth, result.imageHeight, result.thumbnailWidth, result.thumbnailHeight);
          imgInfo.creditsLink = result.url;
          imgInfo.engine = 'Google';
          images.push(imgInfo);
       //}
     });
      this.picker.update(images, this.options);
   },
    pageParameter: function(page) {
      return 'start=' +((page-1)*8+1); // extra parens needed, otherwise will be casted as string
   },
    fetchImages: function(imgSearcher) {
      if (imgSearcher.options.page > 1) {return false;} //use proxy
      var gSearch = new GimageSearch();
      gSearch.setResultSetSize(GSearch.LARGE_RESULTSET);
      gSearch.setSearchCompleteCallback(this, this.updateFunc2, [gSearch, imgSearcher]);
	  gSearch.execute(imgSearcher.options.keywords);	  
      return true;
   },
    updateFunc2: function(gSearch, imgSearcher) {
      var images = [];
      gSearch.results.each(function(result) {
        //if (result.width >= 300 && result.height >= 225) {
          imgInfo = new ImageInfo(result.visibleUrl, result.unescapedUrl, result.tbUrl,
            result.width, result.height, result.tbWidth, result.tbHeight);
          imgInfo.creditsLink = result.originalContextUrl;
          imgInfo.engine = 'Google';
          images.push(imgInfo);
       //}
     });
      imgSearcher.picker.update(images, imgSearcher.options);
   }
 },
 photobucker: {
 }
};

ImageSearcher.prototype = {	
  initialize: function (picker, options) {
    this.picker = picker;
    options = Object.extend({
      engine: 'yahoo',
      page: 1
   }, options || {});
    this.options = options;
    var engineObj = ImageSearcher.engines[options.engine];
	if (!(engineObj.fetchImages && engineObj.fetchImages(this))) {
      ImageSearcher.updateFunc = engineObj.updateFunc.bind(this);
      var searchURL = engineObj.baseURL + encodeURIComponent(options.keywords); 
      if  (options.page) {searchURL += '&'+engineObj.pageParameter(options.page);}
	 setTimeout(function() {appendScript(searchURL);}, 8); //ie6 does not like appendscript from link onclick
   }
 }
} ;

var ImageInfo = Class.create();
ImageInfo.prototype = {
  initialize: function(title, url, thumbUrl, width, height, thumbWidth, thumbHeight, backgroundID, keywords) {
    this.title = title;
    this.url = url;
    this.thumbUrl = thumbUrl;
    this.width = width;
    this.height = height;
    this.thumbWidth = thumbWidth;
    this.thumbHeight = thumbHeight;
    this.backgroundID = backgroundID;
    this.keywords = keywords;
 },
  getThumbImage: function(idealWidth, idealHeight) {
    //var img = new Image();
    var img = Util.newElement('img');
    img.title = this.title + ': ' + this.width + 'x' + this.height;
    img.imgInfo = this;
    // if at first you don't succeed, try, try again!
    img.errFunc = function() {this.src = this.imgInfo.thumbUrl;};
    img.onerror = function() {setTimeout(img.errFunc.bind(img), Math.floor(Math.random()*100+1));};
    img.src = this.thumbUrl;
    if (this.thumbWidth && this.thumbHeight) {
      this.setThumbImageDimensions(img, idealWidth, idealHeight);
   }
    else {
      var self = this;
      img.onload = function() {
        self.thumbHeight = this.height;
        self.thumbWidth = this.width;
        self.setThumbImageDimensions(this, idealWidth, idealHeight);
     };
   }
    return img;
 },
  getKeywords: function() {
    if (this.keywords) {
      return this.keywords.gsub(/\./,' ').strip().gsub(/\s+/,' ').toLowerCase();
   }
    else {return '';}
 },
  setThumbImageDimensions: function(img, idealWidth, idealHeight) {
    if (this.thumbWidth/idealWidth < this.thumbHeight/idealHeight) {
      img.width = idealWidth;
      img.height = this.thumbHeight*idealWidth/this.thumbWidth;
      var offset = (img.height-idealHeight)/2;
      img.style.marginTop = -offset + 'px';
      img.style.marginLeft = '0px';
      img.style.clip = 'rect(' + offset + 'px, ' + idealWidth + 'px, ' + (offset+idealHeight) + 'px, 0px)';
   }
    else {
      img.height = idealHeight;
      img.width = this.thumbWidth*idealHeight/this.thumbHeight;
      var offset = (img.width-idealWidth)/2;
      img.style.marginTop = '0px';
      img.style.marginLeft = -offset+'px';
      img.style.clip = 'rect(0px, ' + (offset+idealWidth) + 'px, ' + idealHeight + 'px, ' + offset + 'px)';
   }
    img.style.width = img.width + 'px';
    img.style.height = img.height + 'px';
    //img.style.position = 'absolute';
 },
  getEngineLabel: function() {
    var label = this.engine || '';
    if (this.engine) {
      if (this.engine == 'flickr') {label += ' user';}
      else {label += ' search result';}
   }
    return label;
 },
  getCreditsHTML: function() {
    var html = '';
    if (this.creditsLink && this.engine) {
      html += 'background from <a href="../includes/'+this.creditsLink+'" target="_blank">' + this.getEngineLabel() + '</a>';
   }
    return html;
 },
  getFormParameters: function() {
    var parms =  'background[original_url]=' + encodeURIComponent(this.url);
    if (this.engine) {parms += '&background[engine]=' + this.engine;}
    if (this.creditsLink) {parms += '&background[credits_link]=' + encodeURIComponent(this.creditsLink);}
    return parms;
 }
};

//****************************************************************************************************************
//ANTES GLOBAL
//****************************************************************************************************************

//funcion encargada de crear el objeto
function externalLinks() {
 if (!document.getElementsByTagName) return;
 var anchors = document.getElementsByTagName("a");
 for (var i=0; i<anchors.length; i++) {
   var anchor = anchors[i];
   if (anchor.getAttribute("href") &&
       anchor.getAttribute("rel") == "external")
     anchor.target = "_blank";
 }
}


 function obj_ajax() {         
	try {                 
		 xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");}
	catch (e) {                 
		 try {                          
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");}
		 catch (E) {                           
			 xmlhttp = false;}
         }
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {                 
 		xmlhttp = new XMLHttpRequest(); }
  return xmlhttp
 }
 
 function extension(str_filename){
	var i = str_filename.length;
	var slicer = String(slicer)
	var ext = String('')
	do{ 
		slicer = str_filename.slice(i-1,i);
		ext = slicer+ext
		i--
	} 
	while(slicer != '.' && i > 1)
	
	ext = ext.toLowerCase();
	return(ext);
}

function esNumero(valor)
{
	if (esEntero(valor) || esDecimal(valor))
		return true;
	return false;
}

function esEntero(valor)
{
  var checkOK = "0123456789-";
  var checkStr = valor;
  var allValid = true;
  var allNum = "";
  for (k = 0;  k < checkStr.length;  k++)
  {
    ch = checkStr.charAt(k);
    for (j = 0;  j < checkOK.length;  j++)
      if (ch == checkOK.charAt(j))
        break;
    if (j == checkOK.length)
    {
      allValid = false;
      break;
    }
    allNum += ch;
  }
  if (!allValid)
  {
    return false;
  }
  return true;
}

function esDecimal(valor)
{
  var checkOK = "0123456789-,.";
  var checkStr = valor;
  var allValid = true;
  var decPoints = 0;
  var allNum = "";
  for (k = 0;  k < checkStr.length;  k++)
  {
    ch = checkStr.charAt(k);
    for (j = 0;  j < checkOK.length;  j++)
      if (ch == checkOK.charAt(j))
        break;
    if (j == checkOK.length)
    {
      allValid = false;
      break;
    }
    if ((ch == ",") || (ch == "."))
    {
      allNum += ".";
      decPoints++;
    }
    else 
		allNum += ch;
  }
  if (!allValid)
    return false;
  if (decPoints > 1 || decPoints == 0)
    return false;
  return true;
}

function Chek_input(campo){
	if (Trim(document.getElementById(campo).value)=="")
		return false;
	return true;
}

function LTrim(s){
	var i=j=0;
	for(i=0; i<=s.length-1; i++)
		if(s.substring(i,i+1) != ' '){
			j=i;
			break;
		}
	return s.substring(j, s.length);
}

function RTrim(s){
	var j=0;
	for(var i=s.length-1; i>-1; i--)
		if(s.substring(i,i+1) != ' '){
			j=i;
			break;
		}
	return s.substring(0, j+1);
}

function Trim(s){
	return LTrim(RTrim(s));
}

function aleatorio(inferior,superior){
	numPosibilidades = superior - inferior
	aleat = Math.random() * numPosibilidades
	aleat = Math.round(aleat)
return parseInt(inferior) + aleat
} 

var Cookie = {
  set: function(name, value, daysToExpire) {
    var expire = '';
    if (daysToExpire != undefined) {
      var d = new Date();
      d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
      expire = '; expires=' + d.toGMTString();
    }
    return (document.cookie = escape(name) + '=' + escape(value || '') + expire);
  },
  get: function(name) {
    var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
    return (cookie ? unescape(cookie[2]) : null);
  },
  erase: function(name) {
    var cookie = Cookie.get(name) || true;
    Cookie.set(name, '', -1);
    return cookie;
  },
  accept: function() {
    if (typeof navigator.cookieEnabled == 'boolean') {
      return navigator.cookieEnabled;
    }
    Cookie.set('_test', '1');
    return (Cookie.erase('_test') === '1');
  }
};

//****************************************************************************************************************
//ANTES API
//****************************************************************************************************************

if (!window['google']) {
window['google'] = {};
}
if (!window['google']['loader']) {
window['google']['loader'] = {};
google.loader.ServiceBase = 'http://www.google.com/uds';
google.loader.ApiKey = 'ABQIAAAA7d4SxF_Vp0WjP56yFVPCBxRJUKQnMwbg0ASlWRohIiUfa1bKKBSp6i7C8o3hv0PICpcSl5AoCylByA';
google.loader.KeyVerified = true;
google.loader.LoadFailure = false;
google.loader.AdditionalParams = '';
(function() { 
function p(a){if(a in s){return s[a]}return s[a]=navigator.userAgent.toLowerCase().indexOf(a)!=-1}
var s={};function x(){return p("msie")}
function y(){return p("safari")||p("konqueror")}
;
function I(a,b){var c=function(){}
;c.prototype=b.prototype;a.o=b.prototype;a.prototype=new c}
var k={};var g={};var o=null;var D=false;function m(a){this.a=a}
m.prototype.b=function(a,b){var c="";if(b!=undefined){if(b["locale"]!=undefined){c+="&hl="+encodeURIComponent(b["locale"])}if(b["nocss"]!=undefined){c+="&output="+encodeURIComponent("nocss="+b["nocss"])}if(b["callback"]!=undefined){var d=z(b["callback"],this.a);c+="&callback="+encodeURIComponent(d)}if(b["other_params"]!=undefined){c+="&"+b["other_params"]}}if(o!=null&&!D){c+="&key="+encodeURIComponent(o);D=true}return google.loader.ServiceBase+"/?file="+this.a+"&v="+a+google.loader.AdditionalParams+
c}
;m.prototype.e=function(){return true}
;function l(a,b,c,d,e,f,E){this.a=a;this.j=b;this.i=c;this.d=d;this.f=e;this.h=f;this.c=E||{}}
I(l,m);l.prototype.b=function(a,b){var c="";if(this.d!=undefined){c+="&"+this.d+"="+encodeURIComponent(o?o:google.loader.ApiKey)}if(this.f!=undefined){c+="&"+this.f+"="+encodeURIComponent(a)}if(b!=undefined&&this.c!=undefined){for(var d in b){if(this.c[":"+d]!=undefined){var e;if(d=="callback"){e=z(b[d],this.a)}else{e=b[d]}var f=this.c[":"+d];if(typeof f=="string"){c+="&"+f+"="+encodeURIComponent(e)}else{c+="&"+f(e)}}else if(d=="other_params"){c+="&"+b[d]}}}google[this.a]={};if(!this.i&&c!=""){c=
"?"+c.substring(1)}w("el",this.a);return this.j+c}
;l.prototype.e=function(){return this.h}
;function J(a,b,c){var d=k[":"+a];if(!d){throw A("Module: '"+a+"' not found!");}else{var e=c&&c["callback"]!=null;if(e&&!d.e()){throw A("Module: '"+a+"' must be loaded before DOM onLoad!");}else if(e){if(g[a]){g[a].actualCallbacks.push(c["callback"])}else if(google[a]){setTimeout(c["callback"],0)}else{t("script",d.b(b,c),e)}}else{t("script",d.b(b,c),e)}}}
function A(a){var b=new Error(a);b.toString=function(){return this.message}
;return b}
function N(a,b){if(b){M(a)}else{r(window,"load",a)}}
function r(a,b,c){if(a.addEventListener){a.addEventListener(b,c,false)}else if(a.attachEvent){a.attachEvent("on"+b,c)}else{var d=a["on"+b];if(d!=null){a["on"+b]=H([c,d])}a["on"+b]=c}}
function H(a){return function(){for(var b=0;b<a.length;b++){a[b]()}}
}
var j=[];function M(a){if(j.length==0){r(window,"load",q);if(!x()&&!y()&&p("mozilla")||window.opera){window.addEventListener("DOMContentLoaded",q,false)}else if(x()){setTimeout(B,10)}else if(y()){setTimeout(C,10)}}j.push(a)}
function B(){try{if(j.length>0){document.firstChild.doScroll("left");q()}}catch(a){setTimeout(B,10)}}
var K={loaded:true,complete:true};function C(){if(K[document.readyState]){q()}else if(j>0){setTimeout(C,10)}}
function q(){for(var a=0;a<j.length;a++){j[a]()}j.length=0}
function L(a){var b=window.location.href;var c;var d=b.length;for(var e in a){var f=b.indexOf(e);if(f!=-1&&f<d){c=e;d=f}}o=c?a[c]:null}
function t(a,b,c){if(c){var d;if(a=="script"){d=document.createElement("script");d.type="text/javascript";d.src=b}else if(a=="css"){d=document.createElement("link");d.type="text/css";d.href=b;d.rel="stylesheet"}document.getElementsByTagName("head")[0].appendChild(d)}else{if(a=="script"){document.write('<script src="'+b+'" type="text/javascript"><\/script>')}else if(a=="css"){document.write('<link href="'+b+'" type="text/css" rel="stylesheet"></link>')}}}
function z(a,b){g[b]=function(){for(var c=0;c<g[b].actualCallbacks.length;c++){setTimeout(g[b].actualCallbacks[c],0)}delete g[b]}
;g[b].actualCallbacks=[a];return"google.loader.callbacks."+b}
function h(a,b){var c=a.split(/\./);var d=window;for(var e=0;e<c.length-1;e++){if(!d[c[e]]){d[c[e]]={}}d=d[c[e]]}d[c[c.length-1]]=b}
h("google.load",J);h("google.setOnLoadCallback",N);h("google.loader.writeLoadTag",t);h("google.loader.setApiKeyLookupMap",L);h("google.loader.callbacks",g);h("google_exportSymbol",h);
function i(){}
var v=i.g=false;var F=i.k=5;var n=i.n=[];var G=i.m=function(){if(!v){r(window,"unload",u);v=(i.g=true)}}
;var w=i.record=function(a,b){G();var c=a+(b?"="+b:"");n.push("r"+n.length+"="+encodeURIComponent(c));if(n.length>F){setTimeout(u,0)}}
;var u=i.l=function(){if(n.length){var a=new Image;a.src=google.loader.ServiceBase+"/stats?"+n.join("&")+"&nocache="+Number(new Date);n.length=0}}
;h("google.loader.recordStat",w);
k[":search"]=new m("search");k[":feeds"]=new m("feeds");k[":language"]=new m("language");k[":maps"]=new l("maps","http://maps.google.com/maps?file=googleapi",true,"key","v",true,{":locale":"hl",":callback":function(a){return"callback="+encodeURIComponent(a)+"&async=2"}
});k[":gdata"]=new l("gdata","http://gd.google.com/gd/api?file=gdata.js",true,"key","v",false);k[":sharing"]=new l("sharing","http://www.google.com/s2/sharing/js",false,"key","v",false,{":locale":"hl"});

 })()
}
if (window['google'] != undefined && window['google']['loader'] != undefined) {
if (!window['google']['search']) {
window['google']['search'] = {};
google.search.CurrentLocale = 'es';
google.search.ShortDatePattern = 'DMY';
google.search.Version = '1.0';
google.search.JSHash = '827f423b91df4dc97aaeb3a17d5711a0';
google.loader.ApiKey = 'ABQIAAAAJXT5qYPgWPtjQtArRwZEohSiADrdezK9JIx4gquGlIsBGsH0eBQKUdwc0J06yEsvH0a4l1p7UfB7Yg';
google.loader.KeyVerified = true;
google.loader.LoadFailure = false;

var _UDS_MSG_SEARCHER_IMAGE = ('Imagen');

var _UDS_MSG_SEARCHER_WEB = ('Web');

var _UDS_MSG_SEARCHER_BLOG = ('Blog');

var _UDS_MSG_SEARCHER_VIDEO = ('V\u00eddeo');

var _UDS_MSG_SEARCHER_LOCAL = ('Local');

var _UDS_MSG_SEARCHCONTROL_SAVE = ('guardar');

var _UDS_MSG_SEARCHCONTROL_KEEP = ('conservar');

var _UDS_MSG_SEARCHCONTROL_INCLUDE = ('incluir');

var _UDS_MSG_SEARCHCONTROL_COPY = ('copiar');

var _UDS_MSG_SEARCHCONTROL_CLOSE = ('cerrar');

var _UDS_MSG_SEARCHCONTROL_SPONSORED_LINKS = ('V\u00ednculos patrocinados');

var _UDS_MSG_SEARCHCONTROL_SEE_MORE = ('ver m\u00e1s...');

var _UDS_MSG_SEARCHCONTROL_WATERMARK = ('recortado de Google');

var _UDS_MSG_SEARCHER_CONFIG_SET_LOCATION = ('Ubicaci\u00f3n relacionada con la b\u00fasqueda');

var _UDS_MSG_SEARCHER_CONFIG_DISABLE_ADDRESS_LOOKUP = ('Inhabilitar la b\u00fasqueda de direcciones');

var _UDS_MSG_SEARCHER_NEWS = ('Noticias');

function _UDS_MSG_MINUTES_AGO(AGE_MINUTES_AGO) {
  return ('hace ' + AGE_MINUTES_AGO + ' minutos');
}

var _UDS_MSG_ONE_HOUR_AGO = ('hace 1 hora');

function _UDS_MSG_HOURS_AGO(AGE_HOURS_AGO) {
  return ('hace ' + AGE_HOURS_AGO + ' horas');
}

function _UDS_MSG_NEWS_ALL_N_RELATED(NUMBER) {
  return ('y ' + NUMBER + ' art\u00edculos relacionados');
}

var _UDS_MSG_NEWS_RELATED = ('Art\u00edculos relacionados');

var _UDS_MSG_BRANDING_STRING = ('con la tecnolog\u00eda de Google');

var _UDS_MSG_SORT_BY_DATE = ('Ordenar por fecha');

var _UDS_MSG_MONTH_ABBR_JAN = ('Ene');

var _UDS_MSG_MONTH_ABBR_FEB = ('Feb');

var _UDS_MSG_MONTH_ABBR_MAR = ('Mar');

var _UDS_MSG_MONTH_ABBR_APR = ('Abr');

var _UDS_MSG_MONTH_ABBR_MAY = ('May');

var _UDS_MSG_MONTH_ABBR_JUN = ('Jun');

var _UDS_MSG_MONTH_ABBR_JUL = ('Jul');

var _UDS_MSG_MONTH_ABBR_AUG = ('Ago');

var _UDS_MSG_MONTH_ABBR_SEP = ('Sep');

var _UDS_MSG_MONTH_ABBR_OCT = ('Oct');

var _UDS_MSG_MONTH_ABBR_NOV = ('Nov');

var _UDS_MSG_MONTH_ABBR_DEC = ('Dic');

var _UDS_MSG_DIRECTIONS = ('direcciones');

var _UDS_MSG_CLEAR_RESULTS = ('borrar resultados');

var _UDS_MSG_SHOW_ONE_RESULT = ('mostrar un resultado');

var _UDS_MSG_SHOW_MORE_RESULTS = ('mostrar m\u00e1s resultados');

var _UDS_MSG_SHOW_ALL_RESULTS = ('mostrar todos los resultados');

var _UDS_MSG_SETTINGS = ('ajustes');

var _UDS_MSG_SEARCH = ('buscar');

var _UDS_MSG_SEARCH_UC = ('Buscar');

var _UDS_MSG_POWERED_BY = ('con la tecnolog\u00eda de');

function _UDS_MSG_LOCAL_ATTRIBUTION(LOCAL_RESULTS_PROVIDER) {
  return ('Directorios empresariales proporcionados por ' + LOCAL_RESULTS_PROVIDER);
}

var _UDS_MSG_SEARCHER_BOOK = ('B\u00fasqueda de libros');

function _UDS_MSG_FOUND_ON_PAGE(FOUND_ON_PAGE) {
  return ('P\u00e1gina ' + FOUND_ON_PAGE);
}

function _UDS_MSG_TOTAL_PAGE_COUNT(PAGE_COUNT) {
  return ('' + PAGE_COUNT + ' p\u00e1ginas');
}

var _UDS_MSG_SEARCHER_BY = ('de');

var _UDS_MSG_SEARCHER_CODE = ('C\u00f3digo');

var _UDS_MSG_UNKNOWN_LICENSE = ('Licencia desconocida');

var _UDS_MSG_SEARCHER_GSA = ('Google Search Appliance');

var _UDS_MSG_SEARCHCONTROL_MORERESULTS = ('M\u00e1s resultados');

var _UDS_MSG_SEARCHCONTROL_PREVIOUS = ('Anterior');

var _UDS_MSG_SEARCHCONTROL_NEXT = ('Siguiente');

var _UDS_MSG_GET_DIRECTIONS = ('Obtener indicaciones');

var _UDS_MSG_GET_DIRECTIONS_TO_HERE = ('Hasta aqu\u00ed');

var _UDS_MSG_GET_DIRECTIONS_FROM_HERE = ('Desde aqu\u00ed');

var _UDS_MSG_CLEAR_RESULTS_UC = ('Borrar resultados');

var _UDS_MSG_SEARCH_THE_MAP = ('buscar en el mapa');

var _UDS_MSG_SCROLL_THROUGH_RESULTS = ('desplazarse por los resultados');

var _UDS_MSG_EDIT_TAGS = ('editar etiquetas');

var _UDS_MSG_TAG_THIS_SEARCH = ('etiquetar esta b\u00fasqueda');

var _UDS_MSG_SEARCH_STRING = ('cadena de b\u00fasqueda');

var _UDS_MSG_OPTIONAL_LABEL = ('etiqueta opcional');

var _UDS_MSG_DELETE = ('suprimir');

var _UDS_MSG_DELETED = ('suprimido');

var _UDS_MSG_CANCEL = ('cancelar');

var _UDS_MSG_UPLOAD_YOUR_VIDEOS = ('subir tu propio v\u00eddeo');

var _UDS_MSG_IM_DONE_WATCHING = ('he acabado de verlo');

var _UDS_MSG_CLOSE_VIDEO_PLAYER = ('cerrar reproductor de v\u00eddeo');

var _UDS_MSG_NO_RESULTS = ('No hay resultados.');

var _UDS_MSG_LINKEDCSE_ERROR_RESULTS = ('El motor de b\u00fasqueda de cupones se est\u00e1 cargando. Vuelve a intentarlo transcurridos unos segundos.');

var _UDS_MSG_COUPONS = ('Cupones');
google.loader.writeLoadTag("script", google.loader.ServiceBase + "/js/search.827f423b91df4dc97aaeb3a17d5711a0.compiled.js");
}
}

//****************************************************************************************************************
//AYAHOO COLOR
//****************************************************************************************************************


/* Copyright (c) 2006 Yahoo! Inc. All rights reserved. */

var YAHOO = function() { return {util: {}} } ();
YAHOO.util.Color = new function() {
  
  // Adapted from http://www.easyrgb.com/math.html
  // hsv values = 0 - 1
  // rgb values 0 - 255
  this.hsv2rgb = function (h, s, v) {
    var r, g, b;
    if ( s == 0 ) {
      r = v * 255;
      g = v * 255;
      b = v * 255;
    } else {

      // h must be < 1
      var var_h = h * 6;
      if ( var_h == 6 ) {
        var_h = 0;
      }

      //Or ... var_i = floor( var_h )
      var var_i = Math.floor( var_h );
      var var_1 = v * ( 1 - s );
      var var_2 = v * ( 1 - s * ( var_h - var_i ) );
      var var_3 = v * ( 1 - s * ( 1 - ( var_h - var_i ) ) );

      if ( var_i == 0 ) { 
        var_r = v; 
        var_g = var_3; 
        var_b = var_1;
      } else if ( var_i == 1 ) { 
        var_r = var_2;
        var_g = v;
        var_b = var_1;
      } else if ( var_i == 2 ) {
        var_r = var_1;
        var_g = v;
        var_b = var_3
      } else if ( var_i == 3 ) {
        var_r = var_1;
        var_g = var_2;
        var_b = v;
      } else if ( var_i == 4 ) {
        var_r = var_3;
        var_g = var_1;
        var_b = v;
      } else { 
        var_r = v;
        var_g = var_1;
        var_b = var_2
      }

      r = var_r * 255          //rgb results = 0 ÷ 255
      g = var_g * 255
      b = var_b * 255

      }
    return [Math.round(r), Math.round(g), Math.round(b)];
  };

  // added by Matthias Platzer AT knallgrau.at 
  this.rgb2hsv = function (r, g, b) {
      var r = ( r / 255 );                   //RGB values = 0 ÷ 255
      var g = ( g / 255 );
      var b = ( b / 255 );

      var min = Math.min( r, g, b );    //Min. value of RGB
      var max = Math.max( r, g, b );    //Max. value of RGB
      deltaMax = max - min;             //Delta RGB value

      var v = max;
      var s, h;
      var deltaRed, deltaGreen, deltaBlue;

      if ( deltaMax == 0 )                     //This is a gray, no chroma...
      {
         h = 0;                               //HSV results = 0 ÷ 1
         s = 0;
      }
      else                                    //Chromatic data...
      {
         s = deltaMax / max;

         deltaRed = ( ( ( max - r ) / 6 ) + ( deltaMax / 2 ) ) / deltaMax;
         deltaGreen = ( ( ( max - g ) / 6 ) + ( deltaMax / 2 ) ) / deltaMax;
         deltaBlue = ( ( ( max - b ) / 6 ) + ( deltaMax / 2 ) ) / deltaMax;

         if      ( r == max ) h = deltaBlue - deltaGreen;
         else if ( g == max ) h = ( 1 / 3 ) + deltaRed - deltaBlue;
         else if ( b == max ) h = ( 2 / 3 ) + deltaGreen - deltaRed;

         if ( h < 0 ) h += 1;
         if ( h > 1 ) h -= 1;
      }

      return [h, s, v];
  }

  this.rgb2hex = function (r,g,b) {
    return this.toHex(r) + this.toHex(g) + this.toHex(b);
  };

  this.hexchars = "0123456789ABCDEF";

  this.toHex = function(n) {
    n = n || 0;
    n = parseInt(n, 10);
    if (isNaN(n)) n = 0;
    n = Math.round(Math.min(Math.max(0, n), 255));

    return this.hexchars.charAt((n - n % 16) / 16) + this.hexchars.charAt(n % 16);
  };

  this.toDec = function(hexchar) {
    return this.hexchars.indexOf(hexchar.toUpperCase());
  };

  this.hex2rgb = function(str) { 
    var rgb = [];
    rgb[0] = (this.toDec(str.substr(0, 1)) * 16) + 
            this.toDec(str.substr(1, 1));
    rgb[1] = (this.toDec(str.substr(2, 1)) * 16) + 
            this.toDec(str.substr(3, 1));
    rgb[2] = (this.toDec(str.substr(4, 1)) * 16) + 
            this.toDec(str.substr(5, 1));
    // gLogger.debug("hex2rgb: " + str + ", " + rgb.toString());
    return rgb;
  };

  this.isValidRGB = function(a) { 
    if ((!a[0] && a[0] !=0) || isNaN(a[0]) || a[0] < 0 || a[0] > 255) return false;
    if ((!a[1] && a[1] !=0) || isNaN(a[1]) || a[1] < 0 || a[1] > 255) return false;
    if ((!a[2] && a[2] !=0) || isNaN(a[2]) || a[2] < 0 || a[2] > 255) return false;

    return true;
  };
}

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

function loadiframe(){
	callback_nurl = "http://www.myflyprofile.myprofilepimp.com/callback.html";
	src_url="http://photobucket.com/plugin?width=320&height=350&largeThumb=&pbaffsite=http://localhost/myflyprofile&bg=%23E0E0E0&border=false&bordercolor=%23000000&linkType=url&textcolor=%23000000&linkcolor=%23000000&media=image&btntxt=Update background width selected&searchenabled=true&searchlinkcolor=&searchbgcolor=";
	//Goto Plugin Location	
	document.getElementById('plugin').src=src_url+'&url='+callback_nurl;
	if(appType==1)
		document.getElementById('plugin2').src=src_url+'&url='+callback_nurl;
}

function photobucket_complete(inurl){
	if(opened=="Pages"){
		$('backImageUrl').value = inurl;
		updateLayoutsBackUrl(inurl,"photobucker");
	}
	else{		
		$('topImageUrl').value = inurl;
		updateTopImagesBackUrl(inurl,"photobucker");
	}
}