/**
 * Extension of wireframe implementation for phones
 */

/**
 * Print ago based on provided datetime
 * 
 * @param mixed datetime
 * @return string
 */
App.Wireframe.Utils['ago'] = function(datetime) {
  return datetime['formatted'];
};

/**
 * Print due data based on provided datetime
 * 
 * @param mixed datetime
 * @return string
 */
App.Wireframe.Utils['due'] = function(datetime) {
  return datetime['formatted'];
};

/**
 * Print due data based on provided datetime
 * 
 * @param string filename
 * @param integer len
 * @return string
 */
App.Wireframe.Utils['shortFilename'] = function(filename, len) {
  if(typeof(len) != 'number' || len < 1) {
    len = 15;
  } // if
  
  if(filename.length > len) {
    return filename.substr(0, len);
  } else {
    return filename;
  } // if
};

/**
 * Return user link based on user object
 *
 * @param Object user
 * @param Boolean use_short_name
 * @return jQuery
 */
App.Wireframe.Utils['userLink'] = function(user, use_short_name) {
  var display_name = use_short_name ? user['short_display_name'] : user['display_name'];
  var link = $('<a class="user_link"></a>').attr('href', user['permalink']).text(display_name);
  
  if(user['id'] == 0) {
    link.addClass('anonymous_user_link');
  } // if
  
  return link;
};

/**
 * Fix for iPhone viewport issue on changing orientation
 */
App.Wireframe.iPhoneOrientationChange = function() {
	
	/**
   * Viewport metatag instance
   *
   * @var jQuery
   */
  var viewport;
  
  // Public interface
  return {
    
    /**
     * Fix orientation change issue
     */
    'fix' : function() {
	    if(navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i)) {
        viewport = $('head').children('meta[name="viewport"]');
        
        $(window).bind('orientation_change', function() {
          if(window.orientation == 90 || window.orientation == -90) {
            //landscape
            viewport.attr('content', 'width=device-width, initial-scale=0.5, maximum-scale=0.5, target-densitydpi=device-dpi');
          } else {
            //portrait
            viewport.attr('content', 'width=device-height, initial-scale=1.0, maximum-scale=0.5, target-densitydpi=device-dpi');
          } // if
        }).trigger('orientation_change');
	    } // if
    }
    
  };
  
}();

/**
 * Logout Handler
 */
App.Wireframe.Logout = function() {
  
  // Public interface
  return {
    
    /**
     * Initialize logout handler
     *
     * @param void
     * @return null
     */
    'init' : function(logout_url) {
    	logout_button = $('#wireframe_action_logout');
    	
    	var popup = $('<div id="logout_dialog" data-role="dialog">' +
                      '<div data-role="header" data-theme="h"></div>' +
                      '<div data-role="content" data-theme="h">' +
                        '<h1 class="ui-corner-top">Are you sure that you want to log out?</h1>' +
                        '<a href="' + logout_url + '" id="logout_link" data-role="button" data-theme="k">Yes</a>' +
                        '<a href="#" id="cancel_link" data-rel="back" data-role="button" data-theme="k">Cancel</a>' +
                      '</div>'+
                    '</div>').appendTo($.mobile.pageContainer);
			
			logout_button.click(function(event) {
				$.mobile.changePage(popup, { transition: 'pop' });
				event.preventDefault();
				
				return false;
			});
			
			var header = popup.find('div[data-role="header"]');

			logout_button.click(function() {
    		setTimeout(function() {
					header.trigger('changed');
				}, 200);
    	});
    	
    	var custom_close_button = '<a href="#" class="ui-btn-left ui-btn ui-btn-up-h ui-btn-icon-notext ui-btn-corner-all ui-shadow" title="Close" data-rel="back" data-icon="delete"></a>';
			
			$('body').delegate('#logout_dialog div[data-role="header"]', 'changed', function() {
    		$(this).find('a').replaceWith(custom_close_button);
    	});
    }
    
  };
  
}();

/**
 * Mobile breadcrumbs implementation
 */
App.Wireframe.MobileBreadCrumbs = function() {
	
	/**
   * Breadcrumbs wrapper instance
   *
   * @var string
   */
  var breadcrumbs_wrapper;
  
  // Public interface
  return {
    
    /**
     * Initialize bread crumbs
     *
     * @param String wrapper_class
     * @param Object breadcrumbs
     */
    'init' : function(wrapper_class, breadcrumbs) {
    	breadcrumbs_wrapper = '.' + wrapper_class;
    	
      $(breadcrumbs_wrapper + ' ul li:not(:first):not(:last)').remove();
    	$(breadcrumbs_wrapper + ' ul > li:first-child').after('<li id="breadcrumb_dots"><a href="#" class="ui-link"></a></li>');
    	
    	var popup = $('<div id="breadcrumbs_popup" data-role="dialog" data-theme="a">' +
                      '<div data-role="header" data-theme="h"></div>' +
                      '<div data-role="content" data-theme="h">' +
                        '<ul data-role="listview" data-theme="h"></ul>' +
                      '</div>'+
                    '</div>').appendTo($.mobile.pageContainer);
      
      var links = popup.find('ul');
      
      $.each(breadcrumbs, function(name, breadcrumb) {
      	var text_link = (name != 'home') ? text_link = breadcrumb.text : '';
      	var li_content = (name != 'final') ? '<a href="' + breadcrumb.url + '">' + text_link + '</a>' : '<span>' + breadcrumb.text + '</span>'
      	
      	$('<li id="' + name + '">' + li_content + '</li>').appendTo(links);
      });
			
			$('#breadcrumb_dots a').click(function(event) {
				$.mobile.changePage(popup, { transition: 'pop' });
				event.preventDefault();
				
				return false;
			});
			
			var header = popup.find('div[data-role="header"]');

			$('#breadcrumb_dots a').click(function() {
    		setTimeout(function() {
					header.trigger('changed');
				}, 200);
    	});
    	
    	var custom_close_button = '<a href="#" class="ui-btn-left ui-btn ui-btn-up-h ui-btn-icon-notext ui-btn-corner-all ui-shadow" title="Close" data-rel="back" data-icon="delete"></a>';
			
			$('body').delegate('div[data-role="header"]', 'changed', function() {
    		$(this).find('a').replaceWith(custom_close_button);
    	});
    }
    
  };
  
}();

/**
 * Confirmation dialogs implementation
 */
App.Wireframe.ConfirmationDialogs = function() {
	
	/**
   * Confirm dialog behavior
   */
  var confirm_dialog = function(link, message) {
  	var dialog_confirmed = confirm(message);
		
		if(dialog_confirmed) {
			window.location = $(link).attr('href');
		} // if
  };
  
  // Public interface
  return {
    
    /**
     * Init confirmation dialogs
     *
     * @param void
     * @param null
     */
    'init' : function() {
      $('body').delegate('#wireframe_action_archive, #wireframe_action_trash, #wireframe_action_unarchive, #wireframe_action_untrash, #wireframe_action_complete, #wireframe_action_reopen', 'click', function() {
      	var action = $(this).attr('id').replace('wireframe_action_', '');
      	
      	if(action == 'archive') {
      		var message = App.lang('Are you sure that you want to move this item to archive?');
      	} else if(action == 'trash') {
      		var message = App.lang('Are you sure that you want to move this item to trash?');
      	} else if(action == 'unarchive') {
      		var message = App.lang('Are you sure that you want to restore this item from archive?');
      	} else if (action == 'untrash') {
      		var message = App.lang('Are you sure that you want to restore this item from trash?');
      	} else if (action == 'complete') {
      		var message = App.lang('Are you sure that you want to complete this item?');
      	} else if (action == 'reopen') {
      		var message = App.lang('Are you sure that you want to reopen this item?');
      	} // if
      	
    		confirm_dialog(this, message);
    		return false;
    	});
    }
    
  };
  
}();

/**
 * Quick tracking time records/expenses implementation
 */
App.Wireframe.QuickTracking = function() {
  
  // Public interface
  return {
    
    /**
     * Initialization
     *
     * @param String navbar_wrapper_class
     * @param JSON quick_tracking_data
     * @return null
     */
    'init' : function(navbar_wrapper_class, quick_tracking_data) {
    	var navbar_wrapper = $('.' + navbar_wrapper_class);
    	
    	var log_time_records = {
    		'title' : App.lang('Log Time Entry'),
    		'link' : navbar_wrapper.find('ul li a#wireframe_action_log_time'),
    		'url' : quick_tracking_data.time_records_add_url
    	};
    	
    	var log_expenses = {
    		'title' : App.lang('Log Expense'),
    		'link' : navbar_wrapper.find('ul li a#wireframe_action_log_expenses'),
    		'url' : quick_tracking_data.expenses_add_url
    	};
    	
    	var quick_tracking_links = [ log_time_records, log_expenses ];
    	
    	$.each(quick_tracking_links, function(k, quick_tracking_link) {
    		var dialog = $('<div id="quick_tracking_dialog" data-role="dialog" data-theme="a">' +
	                      '<div data-role="header" data-theme="h"><span>' + quick_tracking_link.title + '</span></div>' +
	                      '<div data-role="content" data-theme="h">' +
	                        '<ul data-role="listview" data-theme="j"></ul>' +
	                      '</div>'+
	                    '</div>').appendTo($.mobile.pageContainer);
	                    
	      var links = dialog.find('ul');
	      
	      $.each(quick_tracking_data.projects, function(k, project) {
	      	$('<li><a href="' + quick_tracking_link.url.replace('--PROJECT-SLUG--', project.slug) + '"><img class="ui-li-icon" src="' + project.icon + '" alt="" />' + project.name.clean() + '</a></li>').appendTo(links);
	      });
    		
    		quick_tracking_link.link.click(function(e) {
	      	$.mobile.changePage(dialog, { transition: 'pop' });
					e.preventDefault();
					
					return false;
	      });
	      
	      var header = dialog.find('div[data-role="header"]');
	
				quick_tracking_link.link.click(function() {
	    		setTimeout(function() {
						header.trigger('changed');
					}, 200);
	    	});
	    	
	    	var custom_close_button = '<a href="#" class="ui-btn-left ui-btn ui-btn-up-h ui-btn-icon-notext ui-btn-corner-all ui-shadow" title="Close" data-rel="back" data-icon="delete"></a>';
				
				$('body').delegate('div[data-role="header"]', 'changed', function() {
	    		$(this).find('a').replaceWith(custom_close_button);
	    	});
    	});
    }
    
  };
  
}();

/**
 * Quick add implementation
 */
App.Wireframe.QuickAdd = function() {
  
  // Public interface
  return {
    
    /**
     * Initialization
     *
     * @param JSON quick_add_data
     * @return null
     */
    'init' : function(quick_add_data) {
    	var quick_add_wrapper = $('#quick_add_items');
    	var quick_add_item_links = quick_add_wrapper.find('a');
    	
    	quick_add_item_links.each(function() {
    		var quick_add_item_link = $(this);
    		var quick_add_item_url = quick_add_item_link.attr('item_url');
    		var quick_add_item_id = quick_add_item_link.attr('item_id');
    		
    		// check whether project slug placeholder is present
    		if(quick_add_item_url.indexOf('--PROJECT-SLUG--') != -1) {
					var dialog = $('<div id="quick_' + quick_add_item_id + '_dialog" class="quick_add_dialog" data-role="dialog" data-theme="a">' +
			                     '<div data-role="header" data-theme="h"><span>' + App.lang('Select Project') + '</span></div>' +
			                     '<div data-role="content" data-theme="h">' +
			                       '<ul data-role="listview" data-theme="j"></ul>' +
			                     '</div>'+
			                   '</div>').appendTo($.mobile.pageContainer);
		                    
		      var links = dialog.find('ul');
		      
		      $.each(quick_add_data.projects, function(k, project) {
		      	if($.inArray(k, quick_add_data.map[quick_add_item_id]) != -1) {
		      		$('<li><a href="' + quick_add_item_url.replace('--PROJECT-SLUG--', project.slug) + '"><img class="ui-li-icon" src="' + project.icon_big + '" alt="" />' + project.text.clean() + '</a></li>').appendTo(links);
		      	} // if
		      });
		      
		    // check whether company ID placeholder is present
				} else if(quick_add_item_url.indexOf('--COMPANY-ID--') != -1) {
					var dialog = $('<div id="quick_' + quick_add_item_id + '_dialog" class="quick_add_dialog" data-role="dialog" data-theme="a">' +
			                     '<div data-role="header" data-theme="h"><span>' + App.lang('Select Company') + '</span></div>' +
			                     '<div data-role="content" data-theme="h">' +
			                       '<ul data-role="listview" data-theme="j"></ul>' +
			                     '</div>'+
			                   '</div>').appendTo($.mobile.pageContainer);
		                    
		      var links = dialog.find('ul');
		      
		      $.each(quick_add_data.companies, function(k, company) {
		      	var id = k.substring(8);
		      	
		      	if($.inArray(k, quick_add_data.map[quick_add_item_id]) != -1) {
		      		$('<li><a href="' + quick_add_item_url.replace('--COMPANY-ID--', id) + '"><img class="ui-li-icon" src="' + company.icon_medium + '" alt="" />' + company.text.clean() + '</a></li>').appendTo(links);
		      	} // if
		      });
				} // if
    	});
    	
    	quick_add_wrapper.delegate('a', 'click', function(e) {
	      var item_link = $(this);
	      var item_url = item_link.attr('item_url');
	      var item_id = item_link.attr('item_id');
	
	      // check whether project slug or company ID placeholder are present
	      if(item_url.indexOf('--PROJECT-SLUG--') != -1 || item_url.indexOf('--COMPANY-ID--') != -1) {
					$.mobile.changePage($('#quick_' + item_id + '_dialog'), { transition: 'pop' });
					e.preventDefault();
					
					var header = $('body').find('#quick_' + item_id + '_dialog div[data-role="header"]');
		
					setTimeout(function() {
						header.trigger('changed');
					}, 200);
		    	
		    	var custom_close_button = '<a href="#" class="ui-btn-left ui-btn ui-btn-up-h ui-btn-icon-notext ui-btn-corner-all ui-shadow" title="Close" data-rel="back" data-icon="delete"></a>';
					
					$('body').delegate('#quick_' + item_id + '_dialog div[data-role="header"]', 'changed', function() {
		    		$(this).find('a').replaceWith(custom_close_button);
		    	});
				} else {
					window.location = item_url;
				} // if
	      
	      return false;
	    });
    }
    
  };
  
}();

/**
 * Workaround for changing theme on the fly
 */
App.Wireframe.SelectBox = function() {
	
	/**
   * Skinning dialog content (listviews)
   * 
   * @returns null
   */
  var skin_content = function (selectmenu) {
  	var selectmenu_list = $(selectmenu).find('ul');
		
  	if(!selectmenu_list.length) {
  		selectmenu_list = $('body').find('div.ui-page-active ul');
  	} // if
  	
		selectmenu_list.attr('data-theme', 'h');
		selectmenu_list.find('li').each(function() {
			var selectmenu_list_item = $(this);
			var theme = '';
			
			if(selectmenu_list_item.attr('data-role') == 'list-divider') {
				theme = 'm';
			} else {
				theme = 'h';
			} // if
			
			selectmenu_list_item.attr('data-theme', theme);
			if(selectmenu_list_item.hasClass('ui-bar-b')) { selectmenu_list_item.removeClass('ui-bar-b').addClass('ui-bar-'+theme); }
			if(selectmenu_list_item.hasClass('ui-btn-up-f')) { selectmenu_list_item.removeClass('ui-btn-up-f').addClass('ui-btn-up-'+theme) }
		});
  }; // render_necessary dom
  
  // Public interface
  return {
    
    /**
     * Initialize changing select box's theme
     *
     * @param void
     */
    'init' : function() {
    	// Skinning select button 
    	$('div.ui-select').each(function() {
    		$(this).find('a[role="button"]').attr('data-theme', 'l').removeClass('ui-btn-up-f').addClass('ui-btn-up-l');
    	});
    	
    	// Skinning dialog header and content preparation
    	$('div[data-role="dialog"]').each(function() {
    		var select_box_dialog_wrapper = $(this);
    		
    		select_box_dialog_wrapper.addClass('dialog_box_popup').attr('data-theme', 'a').removeClass('ui-body-b').addClass('ui-body-a');
    		select_box_dialog_wrapper.find('div[data-role="header"]').attr('data-theme', 'h').removeClass('ui-bar-a').addClass('ui-bar-h');
    		select_box_dialog_wrapper.find('div[data-role="header"] div.ui-title').remove();
    		
    		var custom_close_button = '<a href="#" class="ui-btn-left ui-btn ui-btn-up-h ui-btn-icon-notext ui-btn-corner-all ui-shadow" title="Close" data-rel="back" data-icon="delete"></a>';
    		select_box_dialog_wrapper.find('div[data-role="header"] a').replaceWith(custom_close_button);
    		
    		var content_block = select_box_dialog_wrapper.find('div[data-role="content"]');
    		content_block.attr('data-theme', 'h');
    	});
    	
    	// Skinning dialog content (listviews)
    	$('.ui-selectmenu').each(function() {
    		$(this).addClass('popup_box').find('.ui-header').remove(); // remove unnecessary header
    		skin_content(this);
    	});
    	
    	$('body').delegate('.ui-selectmenu', 'changed', function() {
    		$(this).each(function() {
	    		skin_content(this);
	    	});
    	});
    	
    	$('select').change(function() {
    		$('.ui-selectmenu').trigger('changed');
    	});
    }
    
  };
  
}();

/**
 * Workaround for changing datebox theme on the fly
 */
App.Wireframe.DateBox = function() {
  
  // Public interface
  return {
    
    /**
     * Initialize changing datebox's theme
     *
     * @param void
     */
    'init' : function() {
    	// Skinning datebox
    	$('div.ui-datebox-container').each(function() {
    		var datebox_container = $(this);
    		
    		datebox_container.attr('data-theme', 'n').removeClass('ui-body-b').addClass('ui-body-n');
    		datebox_container.find(':nth-child(2)').find('div[data-theme="a"]').attr('data-theme', 'n').removeClass('ui-btn-up-a').addClass('ui-btn-up-n');
//    		datebox_container.find(':nth-child(3)').find('input').attr('data-theme', 'p').removeClass('ui-body-e').addClass('ui-body-p');
    		datebox_container.find(':nth-child(4)').find('div[data-theme="a"]').attr('data-theme', 'n').removeClass('ui-btn-up-a').addClass('ui-btn-up-n');
    		datebox_container.find(':nth-child(5)').find('a[data-theme="b"]').attr('data-theme', 'o').removeClass('ui-btn-up-a').addClass('ui-btn-up-o');
    	});
    }
    
  };
  
}();

/**
 * Workaround for changing radio buttons theme on the fly
 */
App.Wireframe.RadioButtons = function() {
  
  // Public interface
  return {
    
    /**
     * Initialize changing radio buttons' theme
     *
     * @param void
     */
    'init' : function() {
    	// Skinning radio buttons
    	$('div.ui-radio').each(function() {
    		var radio_button_container = $(this);
    		
    		radio_button_container.find('label').attr('data-theme', 'i').removeClass('ui-btn-up-c').addClass('ui-btn-up-i');
    	});
    }
    
  };
  
}();

/**
 * Workaround for adding back button on the fly
 */
App.Wireframe.AddBackButton = function() {
  
  // Public interface
  return {
    
    /**
     * Init showing back button
     *
     * @param void
     */
    'init' : function() {
    	var header = $(document).find('div[data-role="header"]');
    	var back_button = $('<a id="wireframe_back_button" href="' + App.Config.data.homepage_url + '" data-rel="back">Back</a>');
    	
    	back_button.appendTo(header);
    }
    
  };
  
}();