/*
 * gadgets.js file should be included first
*/


gadgets.my = function(opt_params) {
  gadgets.Gadget.call(this, opt_params);
  this.serverBase_ = opt_params.serverBase;
  
  this.data = opt_params.extData;// json data attribute passed to back end
  this.instanceId = opt_params.instanceId;
};
gadgets.my.inherits(gadgets.IfrGadget);

//shortcut
gadgets.my.prototype.getId = function() {
    return "gadget-chrome-"+ this.id;
};

gadgets.my.prototype.getIframeUrl = function() {
	
	if (this.wType == undefined || this.wType == APP.WIDGET_SOURCE.WIDGETBOX || this.wType == APP.WIDGET_SOURCE.RSSFEED)
		return this.specUrl;
	else	
    	return this.serverBase_ + 'ifr?' +
	     'container=' + this.CONTAINER +
	     '&mid=' +  this.id +f
	     '&country=' + gadgets.container.country_ +
	     '&lang=' + gadgets.container.language_ +
	     '&view=' + gadgets.container.view_ +
	     (this.specVersion ? '&v=' + this.specVersion : '') +
	     '&parent=' + BASE_URL + 
	     '&rpctoken=' + this.rpcToken +
	     (this.debug ? '&debug=1' : '') +
	     this.getAdditionalParams() +
	     this.getUserPrefsParams() +
	     (this.secureToken ? '&st=' + this.secureToken : '') +
	     '&url=' + encodeURIComponent(this.specUrl) +
	     (this.viewParams ?
	         '&view-params=' +  encodeURIComponent(gadgets.json.stringify(this.viewParams)) : '') +
	     (this.hashData ? '&' + this.hashData : '');
};

//overridden to add in elements for rounding out corners
gadgets.my.prototype.render = function(chrome) {
    if (chrome) {
        this.getContent(function(content) {
            var c = "";
            if (navigator.userAgent.match(/Windows/)) {
                c += " win";
            }
            if (navigator.userAgent.match(/Safari/)) {
                c += " webkit";
            }
			
            //rounded corners...
            /*
            var header = '' +
            '<div class="hd' + c + '">' +
                '<div class="tl"></div>' +
                '<div class="tlf"></div>' +
                '<div class="tr"></div>' +
                '<div class="trf"></div>' +
            '</div>'
            ;
			*/
			
			//rounded corners w/o images
			var header = '' +
            '<div class="hd' + c + '">' +
                '<div class="tl-1" ></div>' +
                '<div class="tl-2" ></div>' +
                '<div class="tlf"></div>' +
                '<div class="tr-1"></div>' +
                '<div class="tr-2"></div>' +
                '<div class="trf"></div>' +
            '</div>'
            ;
			
			/*			
            var footer = '' +
            '<div class="ft">' +
                '<div class="bl"></div>' +
                '<div class="br"></div>' +
            '</div>'
            ;
			*/
			
			var footer = '' +
            '<div class="ft">' +
                '<div class="bl-1" ></div>' +
                '<div class="bl-2" ></div>' +
                '<div class="br-1" ></div>' +
                '<div class="br-2" ></div>' +
            '</div>'
            ;
			
            chrome.innerHTML = header + content + footer;
        });
        
        if (gadgets.container.getView() == "home"){
        	APP.canvas.tweakGadgetWidth($(chrome), this.getIframeId());
       	}else if (gadgets.container.getView() == "canvas"){
   			$(chrome).css("width", "auto");
   		}   
   		  
    }
    
};

/*
	0 - expanded state (expanded)
	1 - collapsed state (closed)
	2 - maximized state (a whole page view)
*/

gadgets.my.prototype.toggleState = APP.widgets.STATUS_EXPANDED;
gadgets.my.prototype.title = "default";
gadgets.my.prototype.icon = APP.widgets.DEFAULT_ICON;

gadgets.my.prototype.setToggleState = function(_state){
	this.toggleState = _state;
};
gadgets.my.prototype.getToggleState = function(){
	return this.toggleState;
};
gadgets.my.prototype.enableThickBox = function(){
	tb_init("#"+this.getCloseButtonId());
};
gadgets.my.prototype.ToggleCollapsed = function(_s){
	
  var gadgetIframe = document.getElementById(this.getIframeId());
  if (gadgetIframe) {
    var gadgetContent = gadgetIframe.parentNode;
    if (_s == APP.widgets.STATUS_FOLDED)
    	gadgetContent.style.display = 'none';
    //else if (_s == APP.widgets.STATUS_MAXIMIZED)
    //	do we need to preserve this state?
  }
};

gadgets.my.prototype.swapToggleStates = function() {
	if ($("#"+this.getToggleFavButtonId()).is("."+this.cssClassTitleFavCloseButton)){
		$("#"+this.getToggleFavButtonId()).removeClass(this.cssClassTitleFavCloseButton);
		$("#"+this.getToggleFavButtonId()).addClass(this.cssClassTitleFavExpandButton);
		
	}else if($("#"+this.getToggleFavButtonId()).is("."+this.cssClassTitleFavExpandButton)){
		$("#"+this.getToggleFavButtonId()).removeClass(this.cssClassTitleFavExpandButton);
		$("#"+this.getToggleFavButtonId()).addClass(this.cssClassTitleFavCloseButton);
	}
	
	if (this.getToggleState() == APP.widgets.STATUS_EXPANDED){
		this.setToggleState(APP.widgets.STATUS_FOLDED);		
		$('#'+ this.getId()).data("layout").state = APP.widgets.STATUS_FOLDED;
		APP.reporting.setPixel({
			action: "widget_expand",
			widgetId: $("#"+ this.getId()).data("layout").typeId
		});
	}
	else{
		this.setToggleState(APP.widgets.STATUS_EXPANDED);		
		$('#'+ this.getId()).data("layout").state = APP.widgets.STATUS_EXPANDED;
		APP.reporting.setPixel({
			action: "widget_collapse",
			widgetId: $("#"+ this.getId()).data("layout").typeId
		});
	}
	//refresh the iframe in case some widgets are not rendered when its initial state is minimized. 	
	
	this.refresh();
	APP.canvas.saveLayout();
};

gadgets.my.prototype.swapMaxMinStates = function() {
	
	//switching button graphics
	if ($("#"+this.getToggleButtonId()).is("."+this.cssClassTitleToggleMaxButton)){
		$("#"+this.getToggleButtonId()).removeClass(this.cssClassTitleToggleMaxButton);
		$("#"+this.getToggleButtonId()).addClass(this.cssClassTitleToggleRestoreButton);
		gadgets.container.setView("canvas");
		
	}else if ($("#"+this.getToggleButtonId()).is("."+this.cssClassTitleToggleRestoreButton)){
		$("#"+this.getToggleButtonId()).removeClass(this.cssClassTitleToggleRestoreButton);
		$("#"+this.getToggleButtonId()).addClass(this.cssClassTitleToggleMaxButton);
		gadgets.container.setView("home");
	}
	
	if ($("#"+this.getToggleButtonId()).hasClass("hover"))
		$("#"+this.getToggleButtonId()).removeClass("hover");
		
	//switching states
	if (this.getToggleState() == APP.widgets.STATUS_MAXIMIZED){
		this.setToggleState(APP.widgets.STATUS_EXPANDED);
		APP.canvas.restoreWidget(this.getId(), this.getIframeId());
		
		$("#"+this.getToolbarButtonId()).show();
		$("#"+this.getCloseButtonId()).show();
		$("#"+this.getToggleFavButtonId()).show();
		
	}else{
		var colId = this.getColumnId();
		var ipos = this.getGadgetPos(colId);
		
		$("#"+this.getToolbarButtonId()).hide();
		$("#"+this.getCloseButtonId()).hide();
		$("#"+this.getToggleFavButtonId()).hide();
		
		if (this.getToggleState() == APP.widgets.STATUS_FOLDED){
			gadgets.container.getGadget(this.id).handleToggle(); 
		}
		
		APP.canvas.maximizeWidget(this.getId(), colId, ipos);
		this.setToggleState(APP.widgets.STATUS_MAXIMIZED);
		
	}
	
	this.refresh();
};

gadgets.my.prototype.getColumnId = function() {
	return $("#"+this.getId()).parent().attr("Id");
};

gadgets.my.prototype.getGadgetPos = function(colId) {
	var oCol = $("#"+APP.canvas.currentPage).find("#"+colId);
	var gadgetId = this.getId();
	var ipos = 0;
	oCol.children().each(function(i){
		if (gadgetId == $(this).attr("Id")){ 
			ipos = i;
			return ipos; 
		}
	}); 
	
	return ipos;
	
};

gadgets.my.prototype.displayPreviewTitleBar = function(bDisplay){
	if (bDisplay){
		$("#"+this.cssClassTitleBar + "-" + this.id).css("cursor", "move");
		$("#"+this.getToolbarButtonId()).show();
		$("#"+this.getToggleButtonId()).show();
		$("#"+this.getCloseButtonId()).show();
		$("#"+this.getToggleFavButtonId()).show();
		$("#"+this.getEditLinkId()).show();
	}else{
		$("#"+this.cssClassTitleBar + "-" + this.id).css("cursor", "default");
		$("#"+this.getToolbarButtonId()).hide();
		$("#"+this.getToggleButtonId()).hide();
		$("#"+this.getCloseButtonId()).hide();
		$("#"+this.getToggleFavButtonId()).hide();
		$("#"+this.getEditLinkId()).hide();
	}
};

gadgets.my.prototype.AddFavIconHoverEvent = function(){
	var iconId = this.getTitleIconId();
	$("#"+this.getToggleFavButtonId())
			.live(
				"mouseover",				
				function() {
					$(this).addClass("hover");
					$("#"+iconId).hide();
				}
			)
			.live(
				"mouseout",
				function() {
					$(this).removeClass("hover");
					$("#"+iconId).show();
				}
			); 
};

gadgets.my.prototype.getToggleButtonId = function() {
    return this.getIframeId() + "_toggleButton";
};
gadgets.my.prototype.getMaximizeButtonId = function() {
    return this.getIframeId() + "_maximizeButton";
};
gadgets.my.prototype.getMinimizeButtonId = function() {
    return this.getIframeId() + "_minimizeButton";
};
gadgets.my.prototype.getSettingsButtonId = function() {
    return this.getIframeId() + "_settingsButton";
};
gadgets.my.prototype.getToolbarButtonId = function(){
	return this.getIframeId() + "_toolbarButton";
};

gadgets.my.prototype.getCloseButtonId = function(){
	return this.getIframeId() + "_closeButton"; 
};

gadgets.my.prototype.getToggleFavButtonId = function(){
	return this.getIframeId() + "_toggleFavButton";
};

gadgets.my.prototype.getTitleIconId = function(){
	return this.getIframeId() + "_titleIcon";
};

gadgets.my.prototype.getEditLinkId = function(){
	return this.getIframeId() + "_editLink";
};

gadgets.my.prototype.setTitle = function(_title){
	this.title = _title;
};
gadgets.my.prototype.getTitle = function(){
	return this.title;
};
gadgets.my.prototype.setIcon = function(_icon){
	if (_icon == undefined || _icon == "undefined" || _icon == "" || _icon == null)
		this.icon = APP.widgets.DEFAULT_ICON;
	else
		this.icon = _icon;
};
gadgets.my.prototype.getIcon = function(){
	return this.icon;
};

gadgets.my.prototype.updateData = function(value){

  var chunk = value;
  
  //use callback to avoid the depencies on the APP.canvas class
  var cbfunc = gadgets.container.getContainerCallBack();
  if (cbfunc == undefined || cbfunc == "" || cbfunc == null )
  	return;
 
  cbfunc(this.instanceId, chunk); 

};


//event handlers
gadgets.my.prototype.handleToolbar = function(){
	
	//APP.utils.debug("handleToolbar: hide_tbadd = " + APP.cookieChip.get("hide_tbadd"));
	
	if ( !TOOLBAR.bInstalled ){
	 	//alert("No Toolbar installed.");
		APP.modal.open({
			type: "tb_dl",
			message: "",
			width: 500,
			height: 450
		});
		/*
		$("#APP-modal .tb_dl .buttons a")
			.unbind("click")
			.click(function(){
				tb_remove();
		});
		*/
		return;
	} else if ( TOOLBAR.NeedsUpgrade( { tb:"mws.settingsCtl",ver:"2.3.50.46" } ) ){
	 	//alert("Sorry, this feature is not supported by your toolbar.");
		APP.modal.open({				
			type: "alert",
			message: "Sorry, this feature is not supported by your toolbar.",
			width: 400,
			height: 500
		});
		$("#APP-modal .alert .ok")
			.unbind("click")
			.click(function(){
				tb_remove();
			});
		return;
	}
	
	if (this.width == undefined || this.width == "undefined")
		this.width = APP.DEFAULT_WBWIDGET_WIDTH;
		
	var sUrl = gBaseUrl + this.specUrl + "&editFrom=tb" + "&widgetType=" + this.wType + "&width=" + this.width + "&height=" + this.height + "&guid=" + this.guid + "&title=" + escape(this.title) + "&icon=" + this.icon;
	var aw_state = addWidget(this.title, sUrl, APP.widgets.TB_DEFAULT_ICON, '0x8001a', this.width, this.height);
/*
1 = success
2 = duplicate (already added)
3 = exceeds maximum
4 = failed 
 */
	if ( aw_state == 1 ){
		if ( parseInt( APP.cookieChip.get("hide_tbadd"), 10 ) != 1 ){
			APP.modal.open({
				type: "tb_add",
				message: "",
				width: 500,
				height: 450
			});
			$("#APP-modal .tb_add .ok")
				.unbind("click")
				.click(function(){
					if ( $("#hide_tbadd_modal").attr("checked") ){
						APP.cookieChip.set( "hide_tbadd", "1" );
					}
					tb_remove();
			});
		}
	} else if ( aw_state == 2 ) {
		APP.modal.open({				
			type: "alert",
			message: "Your toolbar already contains this widget.",
			width: 400,
			height: 500
		});
		$("#APP-modal .alert .ok")
			.unbind("click")
			.click(function(){
				tb_remove();
			});
	} else if ( aw_state == 3 ) {
		APP.modal.open({				
			type: "alert",
			message: "Sorry, cannot add more than 20 buttons.",
			width: 400,
			height: 500
		});
		$("#APP-modal .alert .ok")
			.unbind("click")
			.click(function(){
				tb_remove();
			});
	}else if ( aw_state == 4 ) {
		APP.modal.open({				
			type: "alert",
			message: "Sorry, an error occurred while trying to add the widget.",
			width: 400,
			height: 500
		});
		$("#APP-modal .alert .ok")
			.unbind("click")
			.click(function(){
				tb_remove();
			});
	}

  	saveSettings();
};

gadgets.my.prototype.handleClose = function(){
	$("#"+this.getId()).remove();
	APP.canvas.saveLayout();
};

gadgets.my.prototype.handleMaximize = function() {
	
};
gadgets.my.prototype.handleMinimize = function() {
};
gadgets.my.prototype.expandSettings = function() {

};

gadgets.my.prototype.data = "";
gadgets.my.prototype.instanceId = "";

gadgets.my.prototype.cssClassTitleToggleMaxButton = 'gadgets-gadget-title-maximize-button';
gadgets.my.prototype.cssClassTitleToggleRestoreButton = 'gadgets-gadget-title-restore-button';
gadgets.my.prototype.cssClassTitleToolbarButton = 'gadgets-gadget-title-toolbar-button';
gadgets.my.prototype.cssClassTitleCloseButton = 'gadgets-gadget-title-close-button';
gadgets.my.prototype.cssClassTitleFavCloseButton = 'gadgets-gadget-title-fav-close-button';
gadgets.my.prototype.cssClassTitleFavExpandButton = 'gadgets-gadget-title-fav-expand-button';

gadgets.my.prototype.getTitleBarContent = function(continuation) {
	var editLink = (this.wType == APP.WIDGET_SOURCE.WIDGETBOX) ? ("<a id='" + this.getEditLinkId() + "' href='#' basehref='http://www.widgetbox.com/cgallery/"+gGalleryName+"/widget/" + this.guid + "?wbx_userCtx.oldInstanceId='" + " instanceId='" + this.instanceId + "' widgetWidth='" + this.width+ "' widgetHeight='"+ this.height + "' class='edit-wb'>Edit</a>") : "";
    var	gadgetIconLink = (this.icon != "undefined" && this.icon != undefined)?'<img style="width:16px;height:16px;" id='+this.getTitleIconId()+' class="gadgets-gadget-title-icon" src="'+ this.icon+'" /></a>':'<img style="border:0;padding-left:2px;padding-top:2px;" src="http://ak.imgfarm.com/images/mindspark/widget-portal/widgets/mindspark.ico" ></img></a>';
    var toolbarBtnLink;
    if ( TOOLBAR.bInstalled && !TOOLBAR.NeedsUpgrade( { tb:"mws.settingsCtl",ver:"2.3.50.46" } )) 
		toolbarBtnLink = '<a id="'+ this.getToolbarButtonId()  +'" href="#" onclick="gadgets.container.getGadget('+ this.id +').handleToolbar();return false;" class="' + this.cssClassTitleToolbarButton + '"></a>'; 
    else
    	toolbarBtnLink = '';
    	
    continuation(
        '<div id="' + this.cssClassTitleBar + '-' + this.id + '" class="' + this.cssClassTitleBar + '" onselectstart="return false;">' +
            '<div class="' + this.cssClassTitleButtonBar + '" onselectstart="return false;">' +
                '<a id="'+ this.getToggleFavButtonId()  +'" href="#" onclick="gadgets.container.getGadget('+ this.id +').handleToggle();gadgets.container.getGadget('+ this.id +').swapToggleStates();return false;" class="' + this.cssClassTitleFavExpandButton + '">' +
                gadgetIconLink +
                '<span id="' + this.getIframeId() + '_title" class="' + this.cssClassTitle + '" onselectstart="return false;">' + gadgets.container.getGadget(this.id).getTitle() + '</span>' +
				'<a id="'+ this.getCloseButtonId()  +'" href="#" class="' + this.cssClassTitleCloseButton + '"></a>' +                
                /*'<a id="'+ this.getToggleButtonId() +'" href="#" onclick="gadgets.container.getGadget('+ this.id +').swapMaxMinStates();return false;" class="image-hover ' + this.cssClassTitleToggleMaxButton + '"></a>' +*/
                toolbarBtnLink +
                editLink +				                
                '<br>' +
            '</div>' +
            '<div class="gadgets-gadget-title-button-bar-divider" onselectstart="return false;"></div>' +
            '<div style="clear:both"></div>'+
        '</div>'+
        '</div>'
    );    
};


//Gadget container inheritance
gadgets.my.Container = function() {
    gadgets.IfrContainer.call(this);
};

gadgets.my.Container.inherits(gadgets.IfrContainer);

gadgets.my.Container.prototype.gadgetClass = gadgets.my;
gadgets.my.Container.prototype.containerCallBack = "containerCallBackDefault";
gadgets.my.Container.prototype.setContainerCallBack = function(cb){
	this.containerCallBack = cb;
};
gadgets.my.Container.prototype.getContainerCallBack = function(){
	return this.containerCallBack;
};

gadgets.container = new gadgets.my.Container();



// Gadget Service inheritance
gadgets.my.IfrGadgetService = function(){
	gadgets.IfrGadgetService.call(this);
}

gadgets.my.IfrGadgetService.inherits(gadgets.IfrGadgetService);


gadgets.my.IfrGadgetService.prototype.requestNavigateTo = function(view, opt_params) {
	var id = gadgets.IfrGadgetService.getGadgetIdFromModuleId(this.f);
	gadgets.container.getGadget(id).swapMaxMinStates();
}

gadgets.my.IfrGadgetService.prototype.setUserPref = function(editToken, name, value) {
  
  var id = gadgets.container.gadgetService.getGadgetIdFromModuleId(this.f);
  var gadget = gadgets.container.getGadget(id);
  
  var prefs = gadget.getUserPrefs() || {};
  for (var i = 1, j = arguments.length; i < j; i += 2) {
    prefs[arguments[i]] = arguments[i + 1];
  }
  
  var chunk = '' ;
  for ( x in prefs ) { 
    chunk += "&up_" + name + "=" + escape(prefs[x]) ; 
  } 
  
  
  //use callback to avoid the depencies on the APP.canvas class
  var cbfunc = gadgets.container.getContainerCallBack();
  if (cbfunc == undefined || cbfunc == "" || cbfunc == null )
  	return;
 
  cbfunc(gadget.instanceId, chunk); 
	
}


gadgets.IfrGadgetService = new gadgets.my.IfrGadgetService();




