/*
 *
 *  V.Kondratiev
 *  Flickr AddOn v.2
 *
 *
 */

var flickr2 = $.inherit(Module, {
    __constructor: function(moduleDiv) {
        this.__base(moduleDiv);
        this.type = "flickr2";
        this.isResizing = true;
        this.keepAspectRatio = false;
        if( this.draghandle ) {
	        this.draghandle.addHelpButton();
        }
        var tmp=this;

    },

    // Function to be called only on published pages. Provides access to ajax functionality on published pages.
    initialize: function() {
        // Get the username and thumbnail count from the database,
        // save them to this object, then load the photos
        this.getOptionsFromDb(createRef( this,this.loadContent) );
    },


    // Get the options for this module instance from the database,
    // and possibly perform a callback function afterward
    getOptionsFromDb: function(callbackFunc) {
        _this = this;
        this.ajaxPost('getOptions', {},
            function(data, textSuccess) {
                // Save these options and then possibly call a callback functions
                (callbackFunc || $.noop)(data);
            }
        );
    },


   setOptionsDb: function(opts,callbackFunc) {
				this.ajaxPost('setOptions', opts,
				function(data, textSuccess) {
                // Save these options and then possibly call a callback functions
                (callbackFunc || $.noop)(data);
            }
        );
    },


    saveSettings: function( callbackFunc )
    {
        var module_settings = this.getLocalOptions();
        this.ajaxPost('saveSettings', module_settings,
            function(data, textSuccess)
            {
                // Save these options and then possibly call a callback functions
                (callbackFunc || $.noop)(data);
            }
        );
    },


    updateModule: function( opts ) {
        $("#flickr_content", this.container).parent().parent().addClass("flickr_scroll");
        $("#thumb_container", this.container).html('<img src="/adm/images/tab_loader.gif" />');
        $("#open_close_div", this.container ).attr("style","overflow:hidden; background-color:"+opts.bg_color+";");
        $("#content_div", this.container ).attr("style","background-color:"+opts.bg_color+";color:"+opts.txt_color+";");
        var _this = this;

        //	Put module Title
        if( opts.display_title == "Y" ) {
            $("#title_div", this.container).empty();
            $("<span>").attr("class","flickr_title").html( opts.title ).appendTo( $("#title_div", this.container) );
        }
        else {
            $("#title_div", this.container).empty();
        }

        if( opts.user_name == "" ||  opts.user_name === null ) {
            $("#thumb_container", this.container ).html("Enter flickr user name");
        }
        else {
        		$.getJSON( "http://api.flickr.com/services/rest/?method=flickr.people.findByUsername&api_key=6077ac3e5efcda440b4f2ce697d74e85&username="+encodeURI( opts.user_name )+"&format=json&jsoncallback=?", function(data) {
                if( data.stat == "ok" ) {
                    var nsid = data.user.nsid;

                    // Get Users Photosets and add option to the settings
                    $.getJSON("http://api.flickr.com/services/rest/?method=flickr.photosets.getList&api_key=6077ac3e5efcda440b4f2ce697d74e85&user_id="+encodeURI(nsid)+"&per_page="+opts.thumb_number+"&format=json&jsoncallback=?", function(data) {
                        $("#photoset_group", _this.container).empty();
                        $.each( data.photosets.photoset, function(i,photoset) {
                            $("<option>").attr("class","pso").attr("value",photoset.id).html(photoset.title['_content']).appendTo( $("#photoset_group", _this.container) );
                        });
                        $( 'option[value="'+opts.set_id+'"][class="pso"]', _this.container).attr("selected","selected");
                    });

                    //	Get User Photostream URL and create footer
                    $.getJSON("http://api.flickr.com/services/rest/?method=flickr.urls.getUserPhotos&api_key=6077ac3e5efcda440b4f2ce697d74e85&user_id="+encodeURI(nsid)+"&per_page="+opts.thumb_number+"&format=json&jsoncallback=?", function(data) {
                        var userUrl = data.user.url;
                        $("#footer_div", _this.container ).empty();
                        userLink = '<a href="'+userUrl+'" style="color:'+opts.txt_color+';text-decoration:none;font-weight:bolder;">'+opts.user_name+'</a>';
                        $("<span>").attr("class","footer_txt").html("posted by: "+userLink).appendTo( $("#footer_div", _this.container ) );
                    });

                    //	Get Photos
                    if( opts.set_id == "-MRP-" ) {
                        //	Get most recient photos. Get Photos thumbnails
                        $.getJSON("http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=6077ac3e5efcda440b4f2ce697d74e85&user_id="+encodeURI(nsid)+"&per_page="+opts.thumb_number+"&format=json&jsoncallback=?", function(data) {
                            $("#thumb_container", _this.container).empty();
                            if( data.photos.total > 0 ) {
                                //	Show thumbs on the page
                                $.each(data.photos.photo, function(i,photo){
                                    pictureUrl = "http://farm"+photo['farm']+".static.flickr.com/"+photo['server']+"/"+photo['id']+"_"+photo['secret']+"_z.jpg";
                                    thumbUrl = "http://farm"+photo['farm']+".static.flickr.com/"+photo['server']+"/"+photo['id']+"_"+photo['secret']+"_s.jpg";
                                    $('<a>', {id:photo.id, rel:_this.id, href:pictureUrl, title:photo['title']} )
                                        .lightbox({
                                            fileLoadingImage: '/images/lightbox/loading.gif',
                                            fileBottomNavCloseImage: '/images/lightbox/closelabel.gif',
                                            overlayOpacity : 0.7,
                                            fitToScreen: true
                                        })
                                        .appendTo( $("#thumb_container", _this.container) );
                                    $('<img>', {src:thumbUrl, width:75, height:75 }).addClass('flickr_thumbnail')
                                        .appendTo( $('#'+photo.id), _this.container );
                                });
                            }
                            else {
                                $("#thumb_container", this.container).html('<span style="font-weight:bold;">User does not have any public photos</span>');
                            }
                        });
                    }
                    else {
                        //	Get photos from selected photoset
                        $.getJSON("http://api.flickr.com/services/rest/?method=flickr.photosets.getPhotos&api_key=6077ac3e5efcda440b4f2ce697d74e85&photoset_id="+encodeURI(opts.set_id)+"&per_page="+opts.thumb_number+"&format=json&jsoncallback=?", function(data) {
                            $("#thumb_container", _this.container).empty();
                            //	Show thumbs on the page
                            $.each(data.photoset.photo, function(i,photo) {
                                pictureUrl = "http://farm"+photo['farm']+".static.flickr.com/"+photo['server']+"/"+photo['id']+"_"+photo['secret']+"_z.jpg";
                                thumbUrl = "http://farm"+photo['farm']+".static.flickr.com/"+photo['server']+"/"+photo['id']+"_"+photo['secret']+"_s.jpg";
                                $('<a>', {id:photo.id, rel:_this.id, href:pictureUrl, title:photo['title']} )
                                    .lightbox({
                                        fileLoadingImage: '/images/lightbox/loading.gif',
                                        fileBottomNavCloseImage: '/images/lightbox/closelabel.gif',
                                        overlayOpacity : 0.7,
                                        fitToScreen: true
                                    })
                                    .appendTo( $("#thumb_container", _this.container) );
                                $('<img>', {src:thumbUrl, width:75, height:75 }).addClass('flickr_thumbnail')
                                    .appendTo( $('#'+photo.id), _this.container );
                            });
                        });
                    }
                }
                else {
                    //	User not found
                    $("#thumb_container", _this.container).html('<span style="font-weight:bold; color:red;">'+data.message+'</span>');
                }
            });
        }
    },



    createSettingsPanel: function( opts )
    {
        var _this = this;
        $("<div>").attr("id","settings_div").appendTo( $( "#flickr_content", this.container ) );

        $("<div>").attr("id", "set_username_div").addClass("setting_row").appendTo($("#settings_div", this.container) );
        $("<span>").addClass("settings").html("Flickr Screen Name:").appendTo( $("#set_username_div", this.container) );
        $("<input>").attr("type","text").attr("id","user_name").attr("value",opts.user_name).addClass("settings").attr("name","user_name").appendTo( $("#set_username_div", this.container) );

        $("<div>").attr("id", "set_photosets_div").addClass("setting_row").insertAfter($("#set_username_div", this.container) );
        $("<span>").addClass("settings").html("Available Photosets:").appendTo( $("#set_photosets_div", this.container) );
        $("<select>").attr("id","set_id").attr("name","set_id").addClass("settings").appendTo( $("#set_photosets_div", this.container) );
        $("<optgroup>").attr("id","photostream_group").attr("label","Photostream").appendTo($("#set_id", this.container) );
        $("<option>").attr("value","-MRP-").html("Most recent photos").appendTo($("#photostream_group", this.container) );
        $("<optgroup>").attr("id","photoset_group").attr("label","Sets").appendTo($("#set_id", this.container) );

        $("<div>").attr("id", "set_thumb_number_div").addClass("setting_row").appendTo($("#settings_div", this.container) );
        $("<span>").addClass("settings").html("Number of photos to display:").appendTo( $("#set_thumb_number_div", this.container) );
        $("<input>").attr("type","text").attr("id","thumb_number").attr("name","thumb_number").attr("value",opts.thumb_number).addClass("settings").appendTo( $("#set_thumb_number_div", this.container) );

        $("<div>").attr("id", "set_title_div").addClass("setting_row").appendTo($("#settings_div", this.container) );
        $("<span>").addClass("settings").html("Title:").appendTo( $("#set_title_div", this.container) );
        $("<input>").attr("type","text").attr("id","title").attr("name","title").attr("value",opts.title).addClass("settings").appendTo( $("#set_title_div", this.container) );

        $("<div>").attr("id", "set_display_title_div").addClass("setting_row").appendTo($("#settings_div", this.container) );
        $("<span>").addClass("settings").html("Display title:").appendTo( $("#set_display_title_div", this.container) );
        $("<input>").attr("type","checkbox").attr("id","display_title").attr("name","display_title").addClass("settings").appendTo( $("#set_display_title_div", this.container) );
        if( opts.display_title == "Y" )
           $("#display_title", this.container ).attr("checked","checked");

        $("<div>").attr("id", "set_txt_color_div").addClass("setting_row").appendTo($("#settings_div", this.container) );
        $("<span>").addClass("settings").html("Text color:").appendTo( $("#set_txt_color_div", this.container) );
        $("<select>").attr("id","txt_color").attr("name","txt_color").addClass("settings").appendTo( $("#set_txt_color_div", this.container) );
        $("<option>").attr("class","txtco").attr("value","rgb(255,255,255)").html("White").appendTo( $("#txt_color", this.container) );
        $("<option>").attr("class","txtco").attr("value","rgb(102,102,102)").html("Gray").appendTo( $("#txt_color", this.container) );
        $("<option>").attr("class","txtco").attr("value","rgb(0,0,0)").html("Black").appendTo( $("#txt_color", this.container) );
        $('option[value="'+opts.txt_color+'"][class="txtco"]', this.container ).attr("selected","selected");

        $("<div>").attr("id", "set_txt_bg_color_div").addClass("setting_row").appendTo($("#settings_div", this.container) );
        $("<span>").addClass("settings").html("Background color:").appendTo( $("#set_txt_bg_color_div", this.container) );
        $("<select>").attr("id","bg_color").attr("name","bg_color").addClass("settings").appendTo( $("#set_txt_bg_color_div", this.container) );
        $("<option>").attr("class","bgco").attr("value","rgb(0,0,0)").html("Black").appendTo( $("#bg_color", this.container) );
        $("<option>").attr("class","bgco").attr("value","rgb(102,102,102)").html("Gray").appendTo( $("#bg_color", this.container) );
        $("<option>").attr("class","bgco").attr("value","rgb(255,255,255)").html("White").appendTo( $("#bg_color", this.container) );
        $("<option>").attr("class","bgco").attr("value","none").html("Clear").appendTo( $("#bg_color", this.container) );
        $('option[value="'+opts.bg_color+'"][class="bgco"]', this.container ).attr("selected","selected");

        $("<div>").attr("id","open_close_div").attr("style","overflow:hidden; background-color:black;").appendTo( $( "#flickr_content", this.container ) );
        $("<div>").attr("class","oc_left").html("&nbsp;").appendTo($("#open_close_div", this.container) );
        $("<div>").attr("class","oc_right").html("settings")
            .click( function( a ) {
                $("#settings_div", _this.container ).toggle("slow");
            })
            .appendTo( $("#open_close_div", this.container) );

        $("<div>").attr("id", "set_buttons_div").addClass("setting_row").appendTo($("#settings_div", this.container) );
        $("<input>").attr("type","button").attr("id","save_settins_btn").attr("style","float:right; margin-top:20px;").attr("value","Use These Settings")
            .click( function(){
                _this.saveSettings();
                $("#settings_div", _this.container ).toggle("slow");
            })
            .appendTo( $("#set_buttons_div", this.container) );

        $('input[class="settings"]', this.container).change( function() {	_this.updateModule( _this.getLocalOptions() ); });
        $('select[class="settings"]', this.container).change( function() {	_this.updateModule( _this.getLocalOptions() ); });
    },



	createPreviewPanel: function()
	{
		$("<div>").attr("id","content_div").addClass("content_div").attr("style","background-color:black;color:white;").appendTo( $( "#flickr_content", this.container ) );
		$("<div>").attr("id","title_div").appendTo( $("#content_div", this.container ) );
		$("<div>").attr("id","thumb_container").html("Please, Enter Flickr User Name").appendTo( $("#content_div", this.container ) );
		$("<div>").attr("id","footer_div").appendTo( $("#content_div", this.container ) );
	},



    getLocalOptions: function()
    {
        var display_title;
        var user_name = $("#user_name", this.container ).val();
        if( user_name == $( "#settings_div", this.container ).data('puser') || $( "#settings_div", this.container ).data('puser') == null )
        {
            var set_id = $("#set_id option:selected", this.container ).val();
        }
        else
        {
            var set_id = "-MRP-";
        }

        $( "#settings_div", this.container ).data('puser', user_name );
        var thumb_number = $("#thumb_number", this.container ).val();
        var title = $("#title", this.container ).val();
        if( $("#display_title", this.container )[0].checked )
        {
           display_title = "Y";
        }
        else
        {
           display_title = "N";
        }
        var txt_color = $("#txt_color option:selected", this.container ).val();
        var bg_color = $("#bg_color option:selected", this.container ).val();

        return local_options = { "user_name":user_name, "set_id":set_id, "thumb_number":thumb_number, "title":title, "display_title":display_title, "txt_color":txt_color, "bg_color":bg_color };
    },



   loadContent: function( data ) {
      var _this = this;
      var opts = eval("(" + data.response + ")");

      $("<script>").attr("type","text/javascript").attr("src","/adm/zbl/js/lib/jquery.lightbox.js").appendTo("head");
      var l = $("<link>").attr("type","text/css").attr("rel","stylesheet").appendTo("head");
      l.attr("href","/adm/zbl/css/lib/jquery.lightbox.css");

      if( !( this.isPublished ) ) {
         // Do not load setting on published pages
			/*
   		if( opts ) {
            // Module Exists
				this.createSettingsPanel( opts );
   			$("#settings_div", this.container ).hide();
   		}
   		else {
         //	Brand New Module. Load Default Options
            opts = { "user_name":"", "set_id":"-MRP-", "thumb_number":16, "title":"My Title", "display_title":"Y", "txt_color":"rgb(255,255,255)", "bg_color":"rgb(0,0,0)" };
            this.createSettingsPanel( opts );
         }
			*/
			
			this.createSettingsPanel( opts );
			if( opts.user_name !== null ) {
				$("#settings_div", this.container ).hide();
			}
      }
      this.createPreviewPanel();
      _this.updateModule( opts );
   },


    // This is called as a callback from loadModule.
    // It should also be called directly by modules that overload loadModule and avoid calls to frame2 on init (like customHtml).
    loadModuleCallback: function(data, textStatus) {

        // Store the returned data so we can access it later on
        this.moduleData = data;

        // We need to use innerHTML here because of the (highly probable)
        // chance that the html we get back has <script> in it.  jQuery 1.4
        // tries to be smart and not insert non-standard code.
        this.container[0].innerHTML = data.html;

        // Handle actions to be taken after the saving of this module's settings
        if (this.postSaveData) {
            this.handleModuleSaveResult(this.postSaveData);
            this.setOptionsDb( this.postSaveData.options );
            this.postSaveData = '';
        }

        // Load the retrieved photos into the module div after getting the options from the database
        this.getOptionsFromDb( createRef(this, this.loadContent) );

        this.addDragHandle(data);

        // If a module has declared itself resizing, make it so...
        if (this.isResizing) {
          this.addResizing();
        }
    }
});

