// JavaScript Document
Event.observe(window, 'load', initializeInterface, false);
google.load('search', '1');

//****************************************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
        });
    new Control.ColorPicker("backColor_center", {
        onUpdate: $('backColor_center').onchange
        });
    new Control.ColorPicker("borderColor_center", {
        onUpdate: $('borderColor_center').onchange
        });
    new Control.ColorPicker("headerColor", {
        onUpdate: $('headerColor').onchange
        });

    
    new Control.ColorPicker("headerColorOver", {
        onUpdate: $('headerColorOver').onchange
        });
    new Control.ColorPicker("headerColorText", {
        onUpdate: $('headerColorText').onchange
        });
    new Control.ColorPicker("headerColorTextOver", {
        onUpdate: $('headerColorTextOver').onchange
        });
    new Control.ColorPicker("backColor_header", {
        onUpdate: $('backColor_header').onchange
        });
    new Control.ColorPicker("backColor_body", {
        onUpdate: $('backColor_body').onchange
        });
    new Control.ColorPicker("bodyListColor", {
        onUpdate: $('bodyListColor').onchange
        });
    new Control.ColorPicker("userCommentColor", {
        onUpdate: $('userCommentColor').onchange
        });
    new Control.ColorPicker("commentColor", {
        onUpdate: $('commentColor').onchange
        });

    if(profile_type == 2){
        new Control.ColorPicker("color_sub_headers", {
            onUpdate: $('color_sub_headers').onchange
        });
        new Control.ColorPicker("bg_color_sub_headers_int", {
            onUpdate: $('bg_color_sub_headers_int').onchange
        });
        new Control.ColorPicker("bg_color_sub_headers_blu", {
            onUpdate: $('bg_color_sub_headers_blu').onchange
        });
        new Control.ColorPicker("bg_color_sub_headers_det", {
            onUpdate: $('bg_color_sub_headers_det').onchange
        });
        new Control.ColorPicker("bg_color_sub_headers_com", {
            onUpdate: $('bg_color_sub_headers_com').onchange
        });
        
        
        
        
        new Control.ColorPicker("tableBorderColor", {
            onUpdate: $('tableBorderColor').onchange
        });
        new Control.ColorPicker("tableCornerColor", {
            onUpdate: $('tableCornerColor').onchange
        });
    }

    //inicializo los tabs
    viewInTab(1,'search');
    viewInTab(2,'fontTitle');
    viewInTab(3,'content_backgrounds');
    viewInTab(4,'backboxes');
    viewInTab(5,'heading_options');

    if(profile_type == 2){
        viewInTab(6,'background_options');
    }

    //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');

    //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*6;
        else
            $('moreSpacerHeader').value= 0;
        myLayout.updateStyle();
    }
    form_slider(el, '250');

    
  //configuro el slider del spacio superior
    var secel = document.getElementById("secHeader");
    secel.onDragStart = function() {
        in_elem = document.getElementById('secHeaderin').className = "move2ondrag";
        in_elem = document.getElementById('secHeader').className = "sliderondrag";
    }
    secel.onDrag = function() {
        var value_elem = document.getElementById('secHeader_value');
    };
    secel.onDragStop = function() {
        in_elem = document.getElementById('secHeaderin').className = "move2";
        in_elem = document.getElementById('secHeader').className = "slider";
        valor=Math.round(Number(this.value));
        if(valor>0)
            $('moreSecHeader').value= valor*6;
        else
            $('moreSecHeader').value= 0;
        myLayout.updateStyle();
    }
    form_slider(secel, '250');
    
    
    
    //configuro el drag de los paneles
    new Draggable('panelBrowserImgOpts',{
        revert:false,
        handle: 'topBrowserImgOpts',
        starteffect:false,
        reverteffect:false,
        endeffect:false
    });

    $('wait').hide();
}

//****************************************ACCORDION
//****************************************
var opened="page";
var panelOpened=true;
var viewSel=0;
var updateOpened=false;
var tabOpened= new Array("","","","","","","");
var loadUserLayouts=true;
var theme_parsed=null;

//****************************************PANELS & TABS
//****************************************
function changePreviewMode(){
    if(($("load_layoutId").value!="")&&($("load_profileType").value==profile_type)){
        document.getElementById("previewFrame").src="profile_preview"+profile_type+".php?layoutId="+$("load_layoutId").value+"&profile_mode="+$("profile_mode").value;
    }
    else{
        document.getElementById("previewFrame").src="profile_preview"+profile_type+".php?profile_mode="+$("profile_mode").value;
    }
}

function changeView(opt){
    if(viewSel!=opt){
        switch(opt){
            case 0:{
                $("start").show();
                $("themes").hide();
                $("customize").hide();
                if(viewSel==1)
                    $("btnThemes").removeClassName("btnThemesSel");
                if(viewSel==2)
                    $("btnCustomize").removeClassName("btnCustomizeSel");
                break;
            }
            case 1:{
                $("start").hide();
                $("customize").hide();
                $("btnThemes").addClassName("btnThemesSel");
                if(viewSel==2)
                    $("btnCustomize").removeClassName("btnCustomizeSel");

                if(loadUserLayouts){
                    loadThumbLayouts(-1,profile_type,"",1);
                    loadUserLayouts=false;
                }
                $("themes").appear();
                $("containerThemes").appear();
                break;
            }
            case 2:{
                $("start").hide();
                $("themes").hide();
                if(viewSel==1)
                    $("btnThemes").removeClassName("btnThemesSel");
                $("btnCustomize").addClassName("btnCustomizeSel");
                $("customize").appear();
                break;
            }
        }
        viewSel=opt;
    }
}

function closePanel(){
    if(panelOpened){
        Control.colorPickers.each(function(colorPicker) {
            colorPicker.close();
        });
        hide_browserImg();
        panelOpened=false;
        $("close-panel").addClassName("closed");
        $("close-panel").title="Expand all";
        Effect.SlideUp('panel');
        $("btnClose").hide();
        $("btnOpen").show();
        setTimeout("resize_iframe();",1000);
    }
    else{
        panelOpened=true;
        $("close-panel").removeClassName("closed");
        $("close-panel").title="Collapse all";
        Effect.SlideDown('panel');
        setTimeout("resize_iframe();",1000);
        $("btnOpen").hide();
        $("btnClose").show();
    }
    
    	  
    
}

function showOpts(opt){
    if(opened!=opt){
        Control.colorPickers.each(function(colorPicker) {
            colorPicker.close();
        });
        hide_browserImg();
        $("options_" + opened).hide();
        $('area_'+opened).removeClassName('area_'+opened+'sel');
        opened=opt;
        $("options_" + opened).appear();
        $('area_'+opened).addClassName('area_'+opened+'sel');
        if(profile_type==1){
            $("ul_tabscontent").hide();
            switch(opt){
                case "content":{
                    $("ul_tabscontent").hide();
                    break;
                }
                case "heading":{
                    $("table_headeroptions2").hide();
                    break;
                }
                case "boxes":{
                    $("li_backHeader").hide();
                    $("li_backBody").hide();
                    break;
                }
                case "more":{
                    $("table_moreOptions2").hide();
                    $("table_moreOptions1").show();
                    break;
                }
            }
        }
        else{
            $("ul_tabscontent").hide();
            switch(opt){
                case "content":{
                    $("ul_tabscontent").appear();
                    break;
                }
                case "heading":{
                    $("table_headeroptions2").show();
                    break;
                }
                case "boxes":{
                    $("li_backHeader").show();
                    $("li_backBody").show();
                    break;
                }
                case "more":{
                    $("table_moreOptions1").hide();
                    $("table_moreOptions2").show();
                    break;
                }
            }
        }
    }
}

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
    if(opt=="uploadBackground_page"){
        $("errorUpload").innerHTML="&nbsp;";
        $("errorUpload").hide();
        $("upload_file").value="";
    }
}

function show_browserImg(type,tab){
    $("imageType").value=type;
    viewInTab(1,tab);
    $("url_file").value="";
    new Effect.Appear($("panelBrowserImgOpts"));
}

function hide_browserImg(){
    $("imageType").value="";
    new Effect.Fade($("panelBrowserImgOpts"));
}

function mini_browserImg(){
    new Effect.BlindUp($("contBrowserImgOpts"));
    $("miniBrowserImgOpts").hide();
    $("maxiBrowserImgOpts").show();
}

function maxi_browserImg(){
    new Effect.BlindDown($("contBrowserImgOpts"));
    $("miniBrowserImgOpts").show();
    $("maxiBrowserImgOpts").hide();
}

//******************************************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{
        update_imageByUrl(resu,"upload");
    }
}

function checkUrlFile(){
    $("errorUpload").innerHTML="&nbsp;";
    $("errorUpload").hide();
    if($("url_file").value==""){
        $("errorUpload").innerHTML="Must input a URL";
        $("errorUpload").show();
        return false;
    }
    fileType=extension($("url_file").value);
    if((fileType!=".gif")&&(fileType!=".jpg")&&(fileType!=".png")){
        $("errorUpload").innerHTML="Only jpg, png or gif files";
        $("errorUpload").show();
        return false;
    }
    $('wait').show();
    update_imageByUrl($("url_file").value,"url");
}

//******************************************UPDATE YOUR PROFILE
//******************************************
function onSave(dataResponse){
    $("wait").hide();
    Lightview.show({
        //href: 'submit_layout.php',
        href: 'show_code.php',
        title:"Get Your Code",
        rel: 'iframe',
        options: {
            width:500,
            height:600,
            overlayClose: false/*,
			topclose: true*/
        }
    });
//loadVars='';
//document.getElementById("previewFrame").src="profile_preview"+profile_type+".php";
}

function saveData(){
    $("wait").show();

    //armo el codigo final para copiar con el codigo adicional pata el top image
    if(profile_type==1){
        if($('moreSpacerHeader').value!=0)
            $("cssCode").value+='<a style="border:0;" href="http://www.freecodesource.com" target="_blank"><span></span></a>';
    }
    else{
        if($('moreSpacerHeader').value!=0)
            $('htmlCode').value+='<a style="border:0;" href="http://www.freecodesource.com" target="_blank"></a>';
    }

    jsVars="";
    sep="";
    css_selectors = $H(options);
    css_selectors.each(function(keyVal) {
        var name = keyVal[0];
        if($(name).value=="true"){
            if($(name).checked)
                jsVars+=sep + name + "=true";
            else
                jsVars+=sep + name + "=false";
        }
        else
            jsVars+=sep + name + "=" + $(name).value;

        sep="|";
    });

    _values_send="jsVars="+jsVars+"&cssCode="+$("cssCode").value+"&htmlCode="+$("htmlCode").value+"&profile_type="+profile_type+"&CatID="+$("CatID").value;

    _URL_="session_data.php";
    var ajax = new Ajax.Request( _URL_, {
        postBody: _values_send,
        onComplete: onSave
    });
}

//****************************************THUBNAILS
//****************************************
function loadThumbLayouts(CatID,profile_type,research,page){
    function onLoadThumb(dataResponse){
        $("loadThemes").hide();
        $("containerThemes").update(dataResponse.responseText);
        $("containerThemes").appear();
    }

    function errFunc(){
        error="loadThumbLayouts";
    }

    $("containerThemes").hide();
    $("loadThemes").show();
    _URL_="load_layouts.php?page=" + page + "&profile_type=" + profile_type+ "&CatID=" + CatID + "&research=" + research;
    var ajax = new Ajax.Request( _URL_, {
        method: 'get',
        onComplete: onLoadThumb,
        onFailure:errFunc
    });
}


function submitSearch(){
    loadThumbLayouts($("CatId").value,profile_type,$("research").value,1);
    return false;
}


//****************************************UPDATE THEME AND USER LAYOUTS
//****************************************
function startOver(){
    $('wait').show();
    Control.colorPickers.each(function(colorPicker) {
        colorPicker.close();
    });
    hide_browserImg();

    theme_parsed=false;
    if(($("load_layoutId").value!="")&&($("load_profileType").value==profile_type)){
        $("profile_mode").value="default";
        document.getElementById("previewFrame").src="profile_preview"+profile_type+".php?layoutId="+$("load_layoutId").value;
    }
    else{
        //para que lea valores por defecto
        loadVars='init';
        $("profile_mode").value="default";
        document.getElementById("previewFrame").src="profile_preview"+profile_type+".php";
    }
}

function startBlank(){
    $('wait').show();
    Control.colorPickers.each(function(colorPicker) {
        colorPicker.close();
    });
    hide_browserImg();

    //para que lea valores por defecto
    loadVars='init';
    //incializo todas las variables
    $("profile_mode").value="default";
    document.getElementById("previewFrame").src="profile_preview"+profile_type+".php";
    changeView(0);
}

function loadLayout(layoutId){
    $('wait').show();
    theme_parsed=false;
    $("profile_mode").value="premade";
    document.getElementById("previewFrame").src="profile_preview"+profile_type+".php?layoutId="+layoutId;
}

//****************************************SETS & UPDATES CSS
//****************************************
function initializeVars(jsVars){
    if((jsVars=="")&&($("cssLayout").value=="")){
        if(loadVars=="init"){
            $("cssCode").value='';
            $("htmlCode").value='';
            $("CatID").value=24;

            setDefaults();
        }
    }
    else {
        if(!theme_parsed){
            setDefaults();
            /*if(profile_type==1)
				parserV1();
			else
				parserV2();*/
            theme_parsed=true;
        }

        //valores de un userLayouts
        if(jsVars!=""){
            arrVars=jsVars.split("|");
            for(i=0;i<arrVars.length;i++){
                auxValue=arrVars[i].split("=");
                if((auxValue[1]=="false")||(auxValue[1]=="true")){
                    $(auxValue[0]).checked=(auxValue[1]=="true")?1:0;
                }
                else{
                    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:{
                            if(auxValue[0].lastIndexOf ("Url")!=-1)
                                $(auxValue[0]).value=auxValue[1].replace(/[ ]/gi,"%20");
                            else
                                $(auxValue[0]).value=auxValue[1];
                        };
                    }
                }
            }
            $("moreSpacerHeader").value=$("moreSpacerHeader").value;
            newValue(($("moreSpacerHeader").value/6),'spacerHeader');
        }
    //if($("profile_mode").value=="choose")
    //$("profile_mode").value="premade";
    }
    /*if(profile_type==1)
		changePreviewMode();
	else*/
    myLayout.updateStyle();
}

function setDefaults(){
    //valores por defecto
    css_selectors = $H(options);
    css_selectors.each(function(keyVal) {
        var name = keyVal[0];
        var auxValue = $(keyVal[1]).default_val[profile_type-1];
        var usage = $(keyVal[1]).usage;

        if(usage=="boolean"){
            $(name).checked=(auxValue==true)?1:0;
        }
        else{
            switch(name){
                case 'borderOpc_boxes':{

                    setBorderCss('boxes',auxValue);
                    break;
                }
                case 'borderSize_boxes':{

                    setBorderSize('boxes',auxValue);
                    break;
                }
                case 'fontType_links':{

                    setFontType('title','default',auxValue);
                    break;
                }
                case 'fontType_content':{

                    setFontSize('title','default',auxValue);
                    break;
                }
                case 'fontType_title':{

                    setFontType('content','default',auxValue);
                    break;
                }
                case 'fontSize_links':{

                    setFontSize('content','default',auxValue);
                    break;
                }
                case 'fontSize_content':{

                    setFontType('links','default',auxValue);
                    break;
                }
                case 'fontSize_title':{

                    setFontSize('links','default',auxValue);
                    break;
                }
                default:{
                    if(name.lastIndexOf ("Url")!=-1)
                        $(name).value=auxValue.replace(/[ ]/gi,"%20");
                    else
                        $(name).value=auxValue;
                };
            }
        }
    });
    $("moreSpacerHeader").value='0';
    newValue('0','spacerHeader');

    $("moreTransparency").value='0';
    newValue('0','transparentia');
}

function setBorderCss(element,value){
    if($('borderOpc_'+[element]).value!=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){
    if($('borderSize_'+[element]).value!=value){
        document.getElementById("borderSize_" + element + "_" + $('borderSize_'+[element]).value).className="unselected";
        document.getElementById("borderSize_" + element + "_" + value).className="selected";
        $('borderSize_'+[element]).value=value;
        myLayout.updateStyle();
    }
}


function setFontType(element,item,value){
    if($('fontTypeSel_'+[element]).value!=item){
        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){
    if($('fontSizeSel_'+[element]).value!=item){
        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 update_imageByUrl(url,type){
    updateBack(url);
}

function updateBack(url){
    $($("imageType").value + 'Url').value=url;
    $($("imageType").value + 'None').checked=false;
    myLayout.updateStyle();
}


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 self = this;

        //condiciones referentes al background
        this.update_backImage();
        this.update_backImgContent();
        this.update_headerImage();
        this.update_backImgModule();
        this.update_topImage();
        this.update_secImage();
        if(profile_type==2){
            this.update_backImgHeader();
            this.update_backImgBody();
        }


        if( $('topImageNone').checked || ( $('topImageUrl').value == "" ) ) {

            $('moreSpacerHeader').value=0;
            newValue('0','spacerHeader');
            
        }else{

            if( $('moreSpacerHeader').value == 0 ){
                $('moreSpacerHeader').value = 750;
                newValue('125','spacerHeader');
            }
        }

//        if ( ($('topImageUrl').value!="") && ($('topImageNone').checked==false) ){
//            if($('moreSpacerHeader').value==0){
//                $('moreSpacerHeader').value=750;
//                newValue('125','spacerHeader');
//            }
//        }
//        else{
//            if($('topImageNone').checked==true){
//                $('moreSpacerHeader').value=0;
//                newValue('0','spacerHeader');
//            }
//        }

        if(profile_type==1){
            if($("moreSkinny").checked==true){
                /*cssCode+='table, tr, td{border: none;border-width: 0px;}';
			cssCode+='table table table{width: 100%;padding: 0px;}';
			cssCode+='td td td td{width: .01%;}table, td{width: 300px;padding: 0px;}';
			cssCode+='td.text td.text table table div, td.text td.text table table a img{width:65px !important;}';*/

                cssCode += "\n table table table table {border:0px;}";
                cssCode += "\n td.text table, td.text table td {width:"+$("tptablewidth").value+"px; padding:0px;}";
                cssCode += "\n td.text table table table table, td.text table table table table td {width:0px;}";
                cssCode += "\n table table td {width:10px;}";
                cssCode += "\n div table table td, table table table td {width:auto;}";
                cssCode += "\n td.text td.text table table div, td.text td.text table table a img {height:"+$("tpimageheight").value+"px; width:"+$("tpimagewidth").value+"px !important; border-width:"+$("tpimageborder").value+"px;border-style:solid;}";

            }

            //oculta el background del footer
            if($('backColor').value!="E5E5E5")
                cssCode+='table, tr{background-color: transparent;}';

            if(($('backImgModuleUrl').value!="")||(($('backColor_center').value!='')&&($('backColor_center').value!='FFFFFF'))||($("backColor_centerNone").checked)||($('backImgContentUrl').value!="")||($('backColor_boxes').value!='')||($('borderColor_boxes').value!='')||($('borderOpc_boxes').value!='none')||($('borderSize_boxes').value!='1')||($('backColor_boxesNone').checked==true)){
                cssCode+='table, tr, td{background-color: transparent;border: none;border-width: 0px;}';
                if($("backColor_centerNone").checked==true){
                    cssCode+="table tr td{background-color:transparent;border-style: none;}";
                //cssCode+="table table table,table table table td{background-color: "+$("backColor_boxes").value+"} ";
                }
                else
                if($("backColor_center").value!=""){
                    cssCode+="table td{background-color:" + $("backColor_center").value + ";border-style: none;}";
                    cssCode+="table table table,table table table td{background-color:transparent;border-style: none;}";
                //cssCode+='table, tr, td{background-color: transparent;border: none;border-width: 0px;}';
                }

                cssCode+="table tr td[id='footerWarpper']{background: transparent;border-style: none;}";

                if(($("backColor_boxes").value!="")&&($("backColor_boxesNone").checked==false)){
                    if((($("backImgModuleUrl").value!="")&&($("backImgModuleNone").checked==true))||($("backImgModuleUrl").value==""))
                        //cssCode+="table table table,table table table td{background-color: "+$("backColor_boxes").value+"} ";
                        cssCode+="table table table td{background-color: "+$("backColor_boxes").value+"} ";
                }

                if($("borderOpc_boxes").value!="none"){
                    cssCode+="table table table table{background-color: transparent;border: none;border-width: 0px;}";
                    cssCode+="table table table{border-style: "+$("borderOpc_boxes").value+";}"
                    cssCode+="table table table{border-width:"+$("borderSize_boxes").value+"px;} "
                }
                if($("borderColor_boxes").value!="")
                    cssCode+="table table table{border-color:"+$("borderColor_boxes").value+";}";
                else
                if($("borderOpc_boxes").value!="none")
                    cssCode+="table table table{border-color:000000;}";
            }
        }
        else{
            //nose cssCode+='#footer{background-color:transparent}';
            /*nose if(($("borderOpc_boxes").value!="none")||($("borderSize_boxes").value!=0)){
			cssCode+='div[class~="moduleTop"], div[class~="moduleTop"] div, div[class~="moduleBottom"], div[class~="moduleBottom"] div {background-image:none;}	';
			cssCode+='div[class~="moduleTop"] div div {border-top: none}	div[class~="moduleBottom"] div div { border-bottom:none; }';
			cssCode+='div[class~="moduleMid"] { border-left: none; } div[class~="moduleMid1"] { border-right: none; }';
		}*/
            if(($("backColor_boxesNone").checked==false)&&($("backColor_boxes").value!="")){
                cssCode+="div.module{background-color:#"+$("backColor_boxes").value+"}";
            }
            
//            if( ($("layoutSkinny").checked == true) && ($("layoutWidth").value != "") ){
//                cssCode += "div.wrap{width:" + $("layoutWidth").value + "}";
//            }
        }

        this.css_selectors.each(function(keyVal) {
            if($(keyVal[1]).default_val[profile_type-1] != $(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[profile_type-1];
                    }
                }
                else if (rules.usage == 'replace') {
                    var selectorValue = $(keyVal[0]).value;
                    if (rules[selectorValue] != null) {
                        cssCode += rules[selectorValue];
                    }
                    else {
                        cssCode += rules.css[profile_type-1].gsub('@arg@', selectorValue);
                    }
                }
            }
        });

        //codigo del preview
        if(profile_type==1){
            cssCode=$('cssLayout').value+"<style>.FreeCodeSource { This Layout Was Made Using The New FreeCodeSource.com Profile Editor; }"+cssCode+'</style>';
        }
        else{
            cssCode=$('cssLayout').value+".FreeCodeSource { This Layout Was Made Using The New FreeCodeSource.com Profile 2.0 Editor; }"+cssCode;
        }
        $('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();
    },
    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);
    },
    update_backImage: function(){
        var _value="";
        if(profile_type==1){
            //if ($('backImageUrl').value!=""){
            _value="body {";
            if ($('backImageUrl').value!="")
                _value+="background-image:url(" + $('backImageUrl').value + ");";
            _value+="background-position: "+ $('backPosition').value+";";
            _value+="background-repeat: "+ $('backRepeat').value+";";
            if($('backFixed').checked==true)
                _value+=" background-attachment:fixed;";
            _value+="} ";
            //}
            if($("backImageNone").checked==true){
                _value="body {background-image:none;} ";
            }
        }
        else{
            //if ($('backImageUrl').value!=""){
            _value="body {";
            if ($('backImageUrl').value!="")
                _value+="background-image:url(" + $('backImageUrl').value + ");";
            _value+="background-position: "+ $('backPosition').value+";";
            _value+="background-repeat: "+ $('backRepeat').value+";";
            if($('backFixed').checked==true)
                _value+=" background-attachment:fixed;";
            _value+="} ";
            //}
            if($("backImageNone").checked==true){
                _value="body {background-image:none;} ";
            }
        }
        $('backImage').value=_value;
        return _value;
    },
    update_backImgContent: function(){
        var _value="";
        if(profile_type==1){
            if ($('backImgContentUrl').value!=""){
                _value="table td{";
                _value+="background-image:url(" + $('backImgContentUrl').value + ");";
                _value+="background-position: "+ $('backImgContentPosition').value+";";
                _value+="background-repeat: "+ $('backImgContentRepeat').value+";} ";
                _value+="table table tr td,div table tr td{background: transparent;}";
                if($("backColor_boxesNone").checked==false){
                    _value+="table table table{background-color: "+$("backColor_boxes").value+"}";
                }

            //_value+="table tr td[id='footerWarpper']{background: transparent;}";
            }
            if($("backImgContentNone").checked==true){
                _value="table {background-image:none;} ";
            }
        }
        else{
            if ($('backImgContentUrl').value!=""){
                _value="div.content {";
                _value+="background-image:url(" + $('backImgContentUrl').value + ");";
                _value+="background-position: "+ $('backImgContentPosition').value+";";
                _value+="background-repeat: "+ $('backImgContentRepeat').value+";} ";
            }
            if($("backImgContentNone").checked==true){
                _value="div.content {background-image:none;} ";
            }
        }

        $('backImgContent').value=_value;
        return _value;
    },
    update_backImgModule: function(){
        var _value="";
        if(profile_type==1){
            if($('backImgModuleUrl').value!=""){
                if($("backColor_boxesNone").checked==false){
                    _value="table table table{background-color: "+$("backColor_boxes").value+"}";
                }
                _value+="table table table {";
                //_value+="background-color: "+$("backColor_boxes").value+";";
                _value+="background-image:url(" + $('backImgModuleUrl').value + ");";
                _value+="background-position: "+ $('backImgModulePosition').value+";";
                _value+="background-repeat: "+ $('backImgModuleRepeat').value+";} ";
                _value+="table table table table table{background-image: none}";
                _value+="table table table table table{background-color: transparent}";
            }
            if($("backImgModuleNone").checked==true){
                _value="table table table {background-image:none;} ";
            }
        }
        else{
            if ($('backImgModuleUrl').value!=""){
                if($("backColor_boxesNone").checked==false){
                    _value="div.module{background-color: "+$("backColor_boxes").value+"}";
                }
                _value="div.module {";
                _value+="background-image:url(" + $('backImgModuleUrl').value + ");";
                _value+="background-position: "+ $('backImgModulePosition').value+";";
                _value+="background-repeat: "+ $('backImgModuleRepeat').value+";} ";
            }
            if($("backImgModuleNone").checked==true){
                _value="div.module {background-image:none;} ";
            }
        }
        $('backImgModule').value=_value;
        return _value;
    },
    update_backImgHeader: function(){
        var _value="";
        if ($('backImgHeaderUrl').value!=""){
            _value="h3.moduleHead {";
            _value+="background-image:url(" + $('backImgHeaderUrl').value + ");";
            _value+="background-position: "+ $('backImgHeaderPosition').value+";";
            _value+="background-repeat: "+ $('backImgHeaderRepeat').value+";} ";
        }
        if($("backImgHeaderNone").checked==true){
            _value="h3.moduleHead {background-image:none;} ";
        }
        $('backImgHeader').value=_value;
        return _value;
    },
    update_backImgBody: function(){
        var _value="";
        if ($('backImgBodyUrl').value!=""){
            _value="div.moduleBody {";
            _value+="background-image:url(" + $('backImgBodyUrl').value + ");";
            _value+="background-position: "+ $('backImgBodyPosition').value+";";
            _value+="background-repeat: "+ $('backImgBodyRepeat').value+";} ";
        }
        if($("backImgBodyNone").checked==true){
            _value="div.moduleBody {background-image:none;} ";
        }
        $('backImgBody').value=_value;
        return _value;
    },
    update_headerImage: function(){
        var _value="";
        if(profile_type==1){
            if(($("headerColorNone").checked!=true)&&($("headerColor").value!="2358B8")){
                _value+="body div div table{background: transparent;background-color:"+$("headerColor").value+";}";
            }

            if ($('headerImageUrl').value!=""){
                _value+="body div div table td{background-color: transparent;}";
                _value+="body div div table{";
                _value+="background-image:url(" + $('headerImageUrl').value + ");";
                _value+="background-position: "+ $('headerImagePosition').value+";";
                _value+="background-repeat: "+ $('headerImageRepeat').value+";} ";
            }

            if($("headerImageNone").checked==true){
                _value+="body div div table{background-image:none;} ";
            }
        }
        else{
            if ($('headerImageUrl').value!=""){
                _value="div#header {";
                _value+="background-image:url(" + $('headerImageUrl').value + ");";
                _value+="background-position: "+ $('headerImagePosition').value+";";
                _value+="background-repeat: "+ $('headerImageRepeat').value+";} ";
                _value+="#leaderboard,div#googlebar,#topnav {background-color: transparent;}";
                _value+="#topnav ul,#topnav ul li { border:none;}";
            }

            if($("headerImageNone").checked==true){
                _value="div#header {background-image:none;} ";
                _value+="#topnav ul,#topnav ul li { border:none;}";
            }
        }
        $('headerImage').value=_value;
        return _value;
    },
    update_topImage: function(){
        var _value="";
        if($("topImageNone").checked==true){
            _value=".FreeCodeSourceBannerTop {background-image:none;} ";
        }else if ($('topImageUrl').value!=""){
            _value=".FreeCodeSourceBannerTop {";
            _value+="background-image:url(" + $('topImageUrl').value + ");";
            _value+="background-position: "+ $('topImagePosition').value+";";
            _value+="background-repeat: "+ $('topImageRepeat').value+";} ";

            var topImageCode = '<span class="FreeCodeSourceBannerTop"></span>';
            if( $('htmlCode').value.indexOf(topImageCode) == -1 ){
                $('htmlCode').value += topImageCode;
            }
        }
        $('topImage').value=_value;
        return _value;
    },

    update_secImage: function(){
        var _value="";
        if($("secImageNone") && $("secImageNone").checked==true){
            _value=".contentTop {background-image:none;} ";
        }else if ($('secImageUrl') && $('secImageUrl').value!=""){
            _value=".contentTop {";
            _value+="background-image:url(" + $('secImageUrl').value + ");";
            _value+="background-position: "+ $('secImagePosition').value+";";
            
            var spacer = parseInt($('moreSecHeader').value) || 0;
            if (spacer == 0) spacer = 100;
            var height = spacer + 'px';

            _value += "height: " + height + ";";
            
            _value+="background-repeat: "+ $('secImageRepeat').value+";} ";
            
            
            
        }
	 if ($('secImage')) {
           $('secImage').value=_value;
	 }
        return _value;
    },

    update_headerSpacer: function(){
        var css = '';
        
        var spacer = parseInt($('moreSpacerHeader').value) || 0;
        var height = spacer + 'px';

        if( $('topImageBelowAD').checked ) {
            spacer = spacer > 0 ? spacer + 10 : spacer;
        }

        spacer += 'px';

        var top;
        if(profile_type == 1) {

            top = $('topImageBelowAD').checked ? '100px' : '0';

            css +=  $('topImageBelowAD').checked ? '#leaderboard{padding-bottom:' + spacer + ';}' : 'body.bodyContent {margin-top:' + spacer + ';}';

            css += ".FreeCodeSourceBannerTop{height: " + height + ";position: absolute;width: 800px;margin-left: -400px;top: " + top + ";left: 50%;}"

        }else{
            top = $('topImageBelowAD').checked ? '110px' : '0';

            css +=  $('topImageBelowAD').checked ? '#leaderboard{margin-bottom:' + spacer + ';}' : 'body {padding-top:' + spacer + ';}';

            css += ".FreeCodeSourceBannerTop{height: " + height + ";position: absolute;width: 960px;margin-left: -480px;top: " + top + ";left: 50%;}";
        }

        return css;
    },
    
    update_secheaderSpacer: function(){
        var css = '';
        
        var spacer = parseInt($('moreSecHeader').value) || 0;
        var height = spacer + 'px';

        css += ".contentTop{height: " + height + "}"

        return css;
    },
    
    toggle_layoutWidth: function(){
        if(profile_type==1) return '';

        if( $('layoutSkinny').checked ){
            $('layoutWidth_field').show();
        }else{
            $('layoutWidth_field').hide();
        }
        
        return '';
    },

    update_layoutWidth: function(){
        if(profile_type==1) return '';

        var _value="";
        if( $('layoutSkinny').checked ){
            _value = "div.wrap{width:" + $("layoutWidth").value + "}";
        }
        return _value;
    },

    update_tableColor: function(){
        if(profile_type==1) return '';

        var bg  = $('tableCornerColor').value.toLowerCase();
        var s   = $('tableBorderColor').value.toLowerCase();

        return "div.moduleTop div div {border-top: 1px solid #" + s + ";} div.moduleBottom div div {border-bottom: 1px solid #" + s + ";} div.moduleMid {border-left: solid 1px #" + s + ";} div.moduleMid1 {border-right: solid 1px #" + s + ";} div.moduleTop, div.moduleTop div, div.moduleBottom, div.moduleBottom div {background-color:transparent; background-image:url(http://profile.myspace.com/rc.ashx?bg=" + bg + "&r=6&w=2000&s=" + s + "&sw=1);}";
    }
};

//****************************************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: 'google'
        }, options || {});
        this.pickerDiv = $(options.pickerDiv);
        this.spinner = $(options.spinner);
        this.selectedClass = options.selectedClass;
        this.currentEngine = options.defaultEngine;
        this.searchField = $(options.searchField);
        this.setupEngineLinks();
    },
    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){
            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;
        //le.setBackgroundForCheck(image.imgInfo);
        update_imageByUrl(image.imgInfo.url,"search");
    },
    previewUrl: function() {
        var imgInfo = new ImageInfo('submitted url',$('backImageUrl').value);
    //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 = [];
	  alert(1)
      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) {
            var gSearch = new GimageSearch();
            gSearch.setResultSetSize(GSearch.LARGE_RESULTSET);
            gSearch.setSearchCompleteCallback(this, this.updateFunc, [gSearch, imgSearcher]);
            gSearch.execute(imgSearcher.options.keywords);
            return true;
        },
        updateFunc: function(gSearch, imgSearcher) {
            page_corregida=imgSearcher.options.page-1;
            if(page_corregida!=gSearch.cursor.currentPageIndex)
                gSearch.gotoPage(page_corregida);
            else{
                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);
            return true;
        }
    },
    photobucker: {
}
};

ImageSearcher.prototype = {
    initialize: function (picker, options) {
        this.picker = picker;
        options = Object.extend({
            engine: 'google',
            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 + '; path =/');
    },
    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');
    }
};

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

// {{{ strpos
function strpos( haystack, needle, offset){
    // Find position of first occurrence of a string
    //
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_strpos/
    // +       version: 810.612
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Onno Marsman
    // *     example 1: strpos('Kevin van Zonneveld', 'e', 5);
    // *     returns 1: 14

    var i = (haystack+'').indexOf( needle, offset );
    return i===-1 ? false : i;
}// }}}

function substr( f_string, f_start, f_length ) {
    // Return part of a string
    //
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_substr/
    // +       version: 810.819
    // +     original by: Martijn Wieringa
    // +     bugfixed by: T.Wild
    // +      tweaked by: Onno Marsman
    // *       example 1: substr('abcdef', 0, -1);
    // *       returns 1: 'abcde'
    // *       example 2: substr(2, 0, -6);
    // *       returns 2: ''

    f_string += '';

    if(f_start < 0) {
        f_start += f_string.length;
    }

    if(f_length == undefined) {
        f_length = f_string.length;
    } else if(f_length < 0){
        f_length += f_string.length;
    } else {
        f_length += f_start;
    }

    if(f_length < f_start) {
        f_length = f_start;
    }

    return f_string.substring(f_start, f_length);
}// }}}

// {{{ trim
function trim (str, charlist) {
    // Strip whitespace (or other characters) from the beginning and end of a string
    //
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_trim/
    // +       version: 810.2018
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: mdsjack (http://www.mdsjack.bo.it)
    // +   improved by: Alexander Ermolaev (http://snippets.dzone.com/user/AlexanderErmolaev)
    // +      input by: Erkekjetter
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: DxGx
    // +   improved by: Steven Levithan (http://blog.stevenlevithan.com)
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // *     example 1: trim('    Kevin van Zonneveld    ');
    // *     returns 1: 'Kevin van Zonneveld'
    // *     example 2: trim('Hello World', 'Hdle');
    // *     returns 2: 'o Wor'
    // *     example 3: trim(16, 1);
    // *     returns 3: 6

    var whitespace, l = 0, i = 0;
    str += '';

    if (!charlist) {
        // default list
        whitespace = " \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000";
    } else {
        // preg_quote custom list
        charlist += '';
        whitespace = charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '\$1');
    }

    l = str.length;
    for (i = 0; i < l; i++) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(i);
            break;
        }
    }

    l = str.length;
    for (i = l - 1; i >= 0; i--) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(0, i + 1);
            break;
        }
    }

    return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}// }}}

function loadiframe(){
    callback_nurl = "http://www.freecodesource.com/myspace-editor/callback.html";
    src_url="http://photobucket.com/plugin?width=320&height=350&largeThumb=&pbaffsite=http://www.freecodesource.com/myspace-editor/&bg=%23FFFFFF&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;
}

function photobucket_complete(inurl){
    update_imageByUrl(inurl,"photobucker");
}

function getImgSize(imgSrc)
{
var newImg = new Image();
newImg.src = imgSrc;
var size = new Array(); 
size[0] = newImg.height;
size[1] = newImg.width;
return size;
}


