// ************** LICENCE ****************
/*
	Copyright (c) PORTANEO.

	This file is part of POSH (Portaneo Open Source Homepage) http://sourceforge.net/projects/posh/.

	POSH is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version

	POSH is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with Posh.  If not, see <http://www.gnu.org/licenses/>.
*/
/*
*  POSH opensocial javascript main file
* 
*/

$p = $p || {};
$p.app = $p.app || {};
$p.app.widgets = $p.app.widgets || {};

$p.app.widgets.opensocial = {

   /*
   
                $p.app.widgets.opensocial.createOpensocialWidgetMenu
                
                Create a new way to create widget in the tutorial interface
                
        */
   createOpensocialWidgetMenu:function() {
           $p.tutorial.menus.menusProcess['opensocial']={
                                                            'label':'addOpensocialWidgetMod',
                                                            'labelTxt':'addOpensocialWidgetModTxt',
                                                            'labelDesc':'addOpensocialWidgetModDesc',
                                                            'fct':'$p.app.widgets.opensocial.displayOpensocialForm();',
                                                            'icon':'../images/opensocial.gif'
                                                        };
           $p.tutorial.breadCrumbs['creer']="$p.app.widgets.opensocial.displayOpensocialForm();";
           $p.tutorial.xmlTemplate['content']='';
    },
    /*
    
                $p.app.widgets.opensocial.displayOpensocialForm
                
                Display the opensocial  widget upload form
                
           */
    displayOpensocialForm:function() {
        var l_s="";
        var excludeLinks = new Array();
        $p.tutorial.emptyContent();
        $p.tutorial.breadCrumbs['creer']='displayOpensocialForm();'; 
        $p.tutorial.currentStep='creer';
        excludeLinks.push("visualiser","placer","configurer","picto","valider");
        $p.tutorial.buildBreadCrumbs(excludeLinks);
        
        var tmpcode = $p.tutorial.widgetParameters["code"];
        $p.tutorial.initWidgetParameters();
        $p.tutorial.widgetParameters["code"] = tmpcode;       
      
        l_s += '<table><tbody>\
                <tr>\
                    <td valign="top" width="47%">\
                        <h1>'+lg("addOpensocialWidgetMod")+'</h1><br />\
                        '+lg("msgShindigIntro")+'<br /><br />\
                        '+lang["opensocialFormTxt"]+'<input type="text" name="uploadOpensocial" value="http://" id="uploadOpensocial" size="35" />\
                        &nbsp;&nbsp;<input type="button" name="uploadOpensocialBtn" onclick="$p.app.widgets.opensocial.getOpensocialURL();" id="uploadOpensocialBtn" value="'+lang["opensocialUploadBtnTxt"]+'" />\
                        <br /><br />'+lg("tutorialIgoogleHelp")+'\
                        <br /><br />'+lg("msgOpensocialSamples")+'\
               </td>\
               <td style="background-color:#efefef;padding:15px;" valign="top">\
               <h1 style="color:#5FA6D0;">'+lg("lblFirstUsage")+'</font></h1><br />\
               '+lg("msgRequiresShindig")+'<br />\
               '+lg("msgResizeWidgetWithShindig")+'</td></tr>\
            </tbody></table>';

        $p.print('content',l_s);
    },
    /*
    
                $p.app.widgets.opensocial.getOpensocialURL
                
                Get the opensocial widget code
                
           */
    getOpensocialURL:function() {
        var widgetUrl = $('uploadOpensocial').value;
        if (widgetUrl=="http://") {
            $p.app.alert.show(lg('noUrlSpecified'));
            return false;
        }
        // "http://" is mandatory to connect to the ressource
        if (widgetUrl.substr(0,7) != "http://") {
            $('uploadOpensocial').value = "http://"+widgetUrl;
            widgetUrl = $('uploadOpensocial').value;
        }
        //control if it is an Igoogle widget.
        if ($p.tutorial.controls.isIgoogleWidget(widgetUrl)) {
            widgetUrl = $p.tutorial.controls.getIgoogleWidget(widgetUrl);
            $('uploadOpensocial').value = widgetUrl;
        }

        $p.ajax.call("xml_getwidgetheader.php?url="+$p.string.esc(widgetUrl),
            {
                'type':'load',
                'callback':
                {
                    'function':$p.app.widgets.opensocial.setWidgetCode,
                    'variables':
                    {
                        'url':widgetUrl
                    }
                },
                'source':'html'
            }
        );
        return false;
    },
    /*
    
                $p.app.widgets.opensocial.setWidgetCode
                
                Define widget properties
                
           */
    setWidgetCode:function(response,vars) {
        widgetUrl = vars['url'] || "";  
        var reg = /<?xml/;
        var userPrefs = "";
        if (! response.match(reg) ) {
            $p.app.alert.show(lg("msgCantConnectRessource")+' ('+widgetUrl+')');
            return false;
        }    
        response = $p.string.htmlToText(response);
        response = $p.string.textToXml(response);
      
        if (response.getElementsByTagName("UserPref")[0]) {
            var i=0,err=false;
            while (response.getElementsByTagName("UserPref")[i])
            {
                result=response.getElementsByTagName("UserPref")[i];
                var l_name=$p.ajax.getProp(result,"name","str",false,"");
                var l_dispname=$p.ajax.getProp(result,"display_name","str",false,l_name);
                var l_defval=$p.ajax.getProp(result,"default_value","str",false,"");
                var l_datatype=$p.ajax.getProp(result,"datatype","str",false,"string");     
                userPrefs+='<UserPref name="'+ l_name +'" ';
                userPrefs+= 'datatype="'+l_datatype+'" ';
                userPrefs+= 'default_value="'+l_defval+'" ';
                userPrefs+= 'display_name="'+l_dispname+'" ';
                userPrefs+= '>' + "\r\n";
                if (l_datatype=="enum") {
                    var j=0,l_enum,result2;
                    while (result.getElementsByTagName("EnumValue")[j])
                    {
                        result2=result.getElementsByTagName("EnumValue")[j];
                        l_enum=$p.ajax.getProp(result2,"value","str",false,"");
                        if (j==0&&l_defval=="") l_defval=l_enum;
                        var l_enumd=$p.ajax.getProp(result2,"display_value","str",false,l_enum);
                        userPrefs+='<EnumValue value="'+l_enum+'" display_value="'+l_enumd+'" />'+"\r\n";
                        j++;
                    }
                }
                userPrefs+='</UserPref>'+"\r\n";
                i++;
            }
        }    
        
        $p.app.widgets.opensocial.getViewsFromXML(response);
        $p.tutorial.widgetParameters["link_opensocial"] = widgetUrl;
        $p.tutorial.widgetParameters["format"] = "G";
        $p.tutorial.widgetParameters["code"]=$p.tutorial.xmlTemplate['dtd']
                                             +$p.tutorial.xmlTemplate['opensocialheader']
                                             +userPrefs
                                             +$p.tutorial.xmlTemplate['opensocialcontent']
                                             +$p.tutorial.xmlTemplate['opensocialfooter'];

        eval($p.tutorial.breadCrumbs["configurer"]);
    },
    /*
    
                $p.app.widgets.opensocial.getViewsFromXML
                
                Get the widget views
                
           */
    getViewsFromXML:function(response) {
        var views = new Array()
        var i=0;
        $p.tutorial.widgetParameters["views"] = "";
        if (response.getElementsByTagName("Content")[0]) {
            while (response.getElementsByTagName("Content")[i]) {
                var result = response.getElementsByTagName("Content")[i];
                var view = $p.ajax.getProp(result,"view","str",false,"");
                if (view!="" &&  view.indexOf(',')!=-1) {
                    var viewsList = view.split(',');
                    for (var j=0;j<viewsList.length;j++) {
                        views.push(viewsList[j]);
                    }
                }
                else if (view!="")  views.push(view); 
                else views.push("home");
                i++;
            }
            if (views.length>0) {
                for (var j=0;j<views.length;j++) {
                    if ($p.tutorial.widgetParameters["views"].indexOf(views[j])==-1) {
                        $p.tutorial.widgetParameters["views"] += views[j]+",";
                    }
                }
                var viewslength = $p.tutorial.widgetParameters["views"].length;
                $p.tutorial.widgetParameters["views"] = $p.tutorial.widgetParameters["views"].substring(0,viewslength-1);
            }
            else $p.tutorial.widgetParameters["views"] = "home";
        }
        else $p.tutorial.widgetParameters["views"] = "home";
    }
}