
/**
 * Parent Class for all Arete related classes including backend and frontend
 * @todo Currently frontend got its own root file, that need to be clean and put the shared code here
 *
 * @author Zeeshan Raza
 * @copyright Arete Consulting www.arete-consulting.com
 * @since 20/04/2010
 * @package Arete
 * @version 1.0
 */
if (typeof Arete == "undefined" || !Arete) {
    var Arete = (function(){
    
        var api = {};
        /**
         * Log the message into FireBug console, or alert it if console is not active
         * @param Mixed mxdMsg
         */
        var _log = function(mxdMsg){
            if (typeof console != 'undefined') 
                console.log(mxdMsg);
            else 
                alert(mxdMsg)
        }
        /**
         * Attach date picker
         */
        var _registerDates = function(){
            // using live event on date pickers
           	$('.datePicker, .errorDatePicker').live('click', function() {
           		$(this).datepicker({showOn:'focus', 
           							dateFormat: 'dd/mm/yy', 
           							changeMonth: true,
           							changeYear: true}).focus();
           	});
        };
        /**
         * Check if device is tablet
         */
        var _isTablet = function(){
        	return $('body').hasClass('device-tablet');
        }
        /**
         * Check if user is authenticated
         */
        var _isAuth = function(){
        	return !$('body').hasClass('non-auth');
        }
        /**
         * Remove non-alpha numeric char from the passed string.
         */
        var _removeNonAlpha = function(strInput){
        	return strInput.replace(/[^a-zA-Z 0-9]+/g,'');
        }
        /**
         * Popup the modal window
         */
        var _popUp = function(contents,userConfig){
        	
        	var config={title:'Window',height:200,width:400}
        	$.extend(config,userConfig);
        	
    		if($("#modalWindow").length == 0)
				$('body').append('<div id="modalWindow" class="flora"></div>');

			$("#modalWindow").dialog({
			iframe: true,
			height:config.height,
			width:config.width,
			resizable:false,
			modal: true,
			title:config.title,
			overlay: {
			backgroundColor: '#000',
			opacity: 0.5
			}}).html(contents);
			
			return {
				close : function(){
        		$('#modalWindow').dialog('close');
			},open : function(){
        		$('#modalWindow').dialog('open');
			},
			body :function(contents){
				$('#modalWindow').dialog().html(contents);;
			}
			
			};
        };
        /**
         * Open the link in modal window
         */
        var _registerModalApp = function(){
        	$('.modal-app').live('click',function(e){
        		e.preventDefault();
        		var objClicked = $(this);
        		var popUp = _popUp('',objClicked.data());
        		$('#modalWindow').showLoading();
        		var strUrl = objClicked.attr('href');
        		$.ajax({
        			url:strUrl,
        			success: function(data){
        				popUp.body(data);
        				$('#modalWindow').hideLoading();
        			}
        		});
        	});
        };
        /**
         * Pop the confirm message
         */
        var _popConfirm = function(contents,userConfig){
        	var objDialog = _popUp($('#confirmPop').tmpl({body:contents}),userConfig);
    		// OK action
    		$('#confirmYes').click(function(e) {
    			e.preventDefault();
    			if(typeof userConfig.yes=='undefined')
    				alert('Missing OK Action, provide yes method in parameters');
    			else
    			userConfig.yes();
    		});		
    		
    		// Cancel Action
    		$('#confirmNo').click(function(e) {
    			e.preventDefault();
    			if(typeof userConfig.no=='undefined')
    			objDialog.close();
    			else
    			userConfig.no();
    				
    		});
    	
    		return objDialog;
        }
        /**
         * Register help to popup in new windows
         */
        var _registerPop = function(){
        
            $('.popWindow').die().live('click', function(e){
                e.preventDefault();
                window.open($(this).attr('href'), '_new', 'width=550,height=350,menubar=no,scrollbars=yes,status=no,toolbar=no,resizable=yes');
            });
        };
		/*
		  * Register help to popup in new Jquery UI dialog
         */
        var _registerHelpTip = function(){
        	// Register tool tip only for default device(desktop)
        	if(!_isTablet() && typeof $().tipsy!=='undefined'){
    			$('.toolTip').tipsy({title: 'data-message', gravity: 's',live: true});
        		$('.icons a').tipsy({gravity: 's',live: true});
        	};
        	
		};
		/**
		 * Register pop helper
		 */
		var _registerHelpPop = function(){
			var _cachedData = {};
			var _cachedId = null;
        	var _showPop = function(objClicked){
        		_popUp(_cachedData[_cachedId],{title:objClicked.data('title')||'Help',width:objClicked.data('width')||500,height:objClicked.data('height')||150});
    			$('.help-block').hide();
    			$('#'+objClicked.attr('href').split('#').pop()).show();
    		};
        	$('.helpPop').live('click',function(e){
        		e.preventDefault();
        		var objClicked = $(this);
        		var strUrl = objClicked.attr('href'); 
        		_cachedId = _removeNonAlpha(strUrl);
        		if(typeof _cachedData[_cachedId] =='undefined'){
	        		$.ajax({url:strUrl,success:function(data){
	        			_cachedData[_cachedId] = data;
	        			_showPop(objClicked);
	        			
	        		}});
        		}else{
        			_showPop(objClicked);
        		}
        	});
		}
        /**
         * Popup the confirm box and read the element message
         * @param {Object} objEle
         */
        var _confirm = function(objEle,event){
            var message = objEle.attr('data-message');
            if (typeof message == 'undefined') 
                message = 'Are you sure you want to continue;';
            
            if (!confirm(message)) {
				event.stopImmediatePropagation();
				event.preventDefault();
				return false;
			}
            else
            	return true;
        }
        /**
         * Register help to popup in new windows
         */
        var _confirmClick = function(){
        
            $('.confirmClick').live('click', function(e){
                return _confirm($(this),e);
            });
        };
        /**
         * Register help to popup in new windows
         */
        var _confirmSubmit = function(){
        
            $('.confirmSubmit').bind('submit', function(e){
                return _confirm($(this),e);
            });
        };
        /**
         * Register help to popup in new windows
         */
        var _registerBack = function(){
        
            $('.btnBack').bind('click', function(e){
            	history.go(-1);
            });
        };
		 
        /**
         * Hacking ajax request
         * @param {Object} objOptions
         */
        var _ajaxHack = function(){
            if (typeof $ != 'undefined') {
                var originalAjaxMethod = $.ajax;
                $.ajax = function(objOptions){
                	// Track users
                	if(typeof objOptions.url!='undefined' && typeof _gaq!='undefined'){
                		_gaq.push(['_trackPageview', objOptions.url]);
                	}
                	
                    var originalSuccess = objOptions.success;
                    objOptions.success = function(data, status, objResponse){
                    	if (typeof data !== 'undefined' && typeof data === 'string' && data.charAt(9) === ':') {
                            var arrRedirectInfo = data.split(':');
                            if (arrRedirectInfo[0] === '_redirect') {
                                location.href = arrRedirectInfo[1];
                                return true;
                            }
                            
                        }
                        // Call original success method
                        if (originalSuccess) 
                            originalSuccess(data, status, objResponse);
                    }
                    return originalAjaxMethod(objOptions);
                    
                }
            }
        };
        /**
         * Public methods
         */
        api.popUp = _popUp;
        api.popConfirm = _popConfirm;
        api.removeNonAlpha = _removeNonAlpha;
        api.isTablet = _isTablet;
        api.isAuth = _isAuth;
        /**
    	 * Scroll page back to selector provider or body
    	 */
    	api.scollToTop = function(strSelector) {
    		strSelector = strSelector || 'body';
    		$(strSelector).animate({
    			scrollTop : 0
    		});
    	}
        /**
         * configs
         */
        api.config = {
            debug: false
        };

        /**
         * Javascipt logging
         * @param {Object} mxdMsg
         */
        api.log = function(mxdMsg){
            if (api.config.debug === true) {
                _log(mxdMsg)
            }
        };
        
        /**
         * init method
         */
        api.init = function(){
            _ajaxHack();
            _registerDates();
            _registerPop();
			_confirmClick();
			_confirmSubmit();
			_registerHelpTip();
			_registerHelpPop();
			_registerBack();
			_registerModalApp();
            
        };
        
        /**
         * Gets current url
         */
        api.getUrl = function(){
            return location.href;
        }
        
        /**
         * Clone.
         * Function copied from old Arete class. Must be reviewd
         */
        api.clone = function(Super){
            var clonedObject = {}
            for (key in Super) {
                if (Super.hasOwnProperty(key)) {
                    clonedObject[key] = Super[key];
                }
            }
            return clonedObject;
        };
        
		/**
		 * Require the chain of modules
		 */
		api.require = function(mxdModuleName, callback) {
			// Check if module already loaded
			var _isAlreadyLoaded = function(strSingleModule){
				var arrModules = strSingleModule.split('.');
				var namespace = window;
				var _loaded = true;
				$.each(arrModules, function(index, strModule) {
					if(typeof namespace[strModule]!='undefined'){
						namespace = namespace[strModule];
					}else{
						_loaded = false;
						return false;
					}
				});
				return _loaded;
			}
			
			if(typeof mxdModuleName==='object'){
				var tmpObj = [];
				$.each(mxdModuleName,function(index,strSingleModulePath){
					tmpObj[tmpObj.length] = Arete.config.MODULE_ROOT + strSingleModulePath.split('.').join('/') + '.js?'+new Date().getTime();
				});
				require(tmpObj, callback);
				return;
			};
			var arrModulePath = mxdModuleName.split('.');
			var arrModules = [];
			var strSingleModulePath = '';
			var strSingleModule = '';
			$.each(arrModulePath, function(index, strModule) {
				if (strSingleModulePath === '') {
					strSingleModulePath = strModule;
					strSingleModule = strModule;
				} else {
					strSingleModulePath += '/' + strModule;
					strSingleModule += '.' + strModule;
				}
				// Load module if not already loaded
				if (!_isAlreadyLoaded(strSingleModule)){
					arrModules[arrModules.length] = Arete.config.MODULE_ROOT
							+ strSingleModulePath + '.js?'+new Date().getTime();
				}
			});
			var loader = function(ctr) {
				require([ arrModules[ctr] ], function() {
					if (ctr++ < arrModules.length)
						loader(ctr);
					else
						callback();
				});
			}
			loader(0);
		};
		
		api.getContext = function(defaultContext) {
			if (typeof Arete.config['appContext'] !== 'undefined') {
				return Arete.config['appContext'];
			} else {
				if (typeof defaultContext !== 'undefined') {
					return defaultContext;
				} else {
					return document;
				}

			}
		};
		api.setContext = function(context) {
			Arete.config['appContext'] 	= context;	
		};
        return api;
    })();
};
// Run the initlization
$().ready(function(){
    Arete.init();
});


