/*
 *
 *  V.Kondratiev
 *  Flickr AddOn
 *
 *
 */

var flickr = $.inherit(Module, {
    __constructor: function(moduleDiv) {
        this.__base(moduleDiv);
        this.type = "flickr";
        this.isResizing = true;
        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.loadPhotos) );
    },


    // 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);
            }
        );
    },
    

	loadPhotos: function(data) {
   		var opts = eval("(" + data.response + ")");
         
    	var dt = new Array();
      	dt['container'] = this.container;
      	dt['instance'] = this.instId;
      	dt['thumbCount'] = opts.thumbCount;
		dt['flickrName'] = opts.flickrName;
		if( opts.tags != null ? dt['tags'] = opts.tags : dt['tags'] = "" );

      	//	Get user NSID by flickr user name
      	$.getJSON( "http://api.flickr.com/services/rest/?method=flickr.people.findByUsername&api_key=6077ac3e5efcda440b4f2ce697d74e85&username="+encodeURI(dt['flickrName'])+"&format=json&jsoncallback=?", dt, function(data) {
      		if( data.stat == "ok" ) {
         		var nsid = data.user.nsid;
            	$('#thumbContainer',dt['container']).empty();
            	//	get users photostream url (if username combined from several words it will differ from normal url
            	$.getJSON("http://api.flickr.com/services/rest/?method=flickr.urls.getUserPhotos&api_key=6077ac3e5efcda440b4f2ce697d74e85&user_id="+encodeURI(nsid)+"&per_page="+dt['thumbCount']+"&format=json&jsoncallback=?", dt, function(data){
            		var userUrl = data.user.url;
               		$("#photostreamUrl",dt['container']).attr("href", userUrl );
               		//	Get Photos thumbnails
               		$.getJSON("http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=6077ac3e5efcda440b4f2ce697d74e85&user_id="+encodeURI(nsid)+"&per_page="+dt['thumbCount']+"&tags="+encodeURI(dt['tags'])+"&format=json&jsoncallback=?", dt, function(data){					
               			//	Show thumbs on the page
                 		thumbContainer = $("#thumbContainer",dt['container']);
                 		$.each(data.photos.photo, function(i,photo){
                 			// Get Bigger picture url and preload it
                     		picUrl = "http://farm"+photo['farm']+".static.flickr.com/"+photo['server']+"/"+photo['id']+"_"+photo['secret']+"_z.jpg";
                 			//	Get thumb url
                     		thumbUrl = "http://farm"+photo['farm']+".static.flickr.com/"+photo['server']+"/"+photo['id']+"_"+photo['secret']+"_s.jpg";
                     		$("<img/>").attr("src", thumbUrl ).attr("class","flickrImg").appendTo( thumbContainer )
                     			.wrap("<div id='flickrSlide' class='flickrSlide'></div>")
                       			.wrap("<a rel='"+dt['flickrName']+"' href='"+picUrl+"' title='"+photo['title']+"'></a>");
                  		});
               		});
            	});
            	$(document).ready( function () {
            		setTimeout( function(){$("a[rel='"+dt['flickrName']+"']").colorbox();}, 2000 );
            	});
            }
      		else {
      			// User not found - Show error
         		$('#albumTitle',dt['container']).remove();
         		$("#thumbContainer",dt['container']).attr("style","color:red;").html("<p>"+data.stat + " :: " + data.message + "</p>");
         		$('#albumFooter',dt['container']).remove();		
      		}
		});
	},
    

    // 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.loadPhotos));

        this.addDragHandle(data);

        // If a module has declared itself resizing, make it so...
        if (this.isResizing) {
          this.addResizing();
        }
    },
    
    // Appropriately size modules based upon their location on the page
    appropriatelyResize: function(floatValue) {

        var moduleContainerDiv = $('.module-container', this.element);

        var adjustedModuleWidth = null;
        var adjustedModuleHeight = null;

        // Resize the image appropriately according to the region in which it was dropped
        if ((this.element.parent().attr('id') == 'header') || (this.element.parent().attr('id') == 'footer')) {
                adjustedModuleHeight = '100px';
        }
        else if (this.element.parent().attr('id') == 'content') {
            if (floatValue == 'none') {
                adjustedModuleWidth = this.element.parent().width() + 'px';
            }
            else {
                adjustedModuleWidth = (this.element.parent().width() * .5) + 'px';
            }
        }
        else if (this.element.parent().attr('id') == 'sidebar') {
            if (floatValue == 'none') {
                adjustedModuleWidth = this.element.parent().width() + 'px';
            }
            else {
                adjustedModuleWidth = (this.element.parent().width() * .5) + 'px';
            }
        }

        // Resize the module div and stretch the image to match the height and width of the module div
        if (adjustedModuleWidth) {
            this.element.css({ 'width': adjustedModuleWidth });
        }

        if (adjustedModuleHeight) {
            this.element.css({ 'height': adjustedModuleHeight });
        }

        if (adjustedModuleWidth || adjustedModuleHeight) {
            moduleContainerDiv.css({ 'width': '100%', 'height': '100%' });
        }
    },


    /* Adds resize handles and functionality to the module div */
    addResizing: function() {
        var _this = this;
        var aspectRatio = 0;

        // Destroy the current handle (needed for returning from preview mode) and create a new one
        this.container.resizable('destroy');

        this.container.resizable({
            handles: "se", 
            containment: this.element.parent(), 
            minHeight: 40,
            minWidth: 84,
            autoHide: false,
            start: function(e, ui) {
                    _this.element.unbind('mouseleave');
                    aspectRatio = ui.originalSize.height / ui.originalSize.width;
                    $("<div />", { "class": "resizeDimensions" }).appendTo(_this.container).fadeIn("fast");

                    _this.element.find('embed').css('height', '100%');
                },

            resize: function(e, ui) {
                    var w = _this.container.width();
                    var h = _this.container.height();

                    _this.onResize(e, ui);

                    _this.element.css({
                        width: w + "px",
                        height: h + "px"
                    });

                    _this.setDragHandlePosition();
                    $('.resizeDimensions', _this.container).html(w + "x" + h);
                },

            stop: function(e, ui) {
                    _this.element.bind('mouseleave', function() {
                        if (_this.doOnMouseOut) {
                            _this.doOnMouseOut();
                        }
                        else {
                            _this.draghandle.fadeOut(_this.mouseFadeOutTime);
                        }
                    });

                    $(".resizeDimensions", _this.container).fadeOut("fast").remove();
                } 
        });
    }
});

