
/**
 * Parent Class for all Arete related classes
 *
 * @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(){
    
        /**
         * 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)
        }
        
		/**
		 * Fix IE related issues, 
		 * Try to fix them with CSS, if not possible, only then use this method
		 */
		var _ieFixes = function (){
			if(!$.browser.msie)
				return;
				
			// Giving margin to market names	
			$('.option_market').each(function(){
				$(this).text('  '+$(this).text());
			});
		}
		
        /**
         * Hacking ajax request
         * @param {Object} objOptions
         */
        var _ajaxHack = function(){
            if (typeof $ != 'undefined') {
                var originalAjaxMethod = $.ajax;
                $.ajax = function(objOptions){
                    var originalSuccess = objOptions.success;
                    objOptions.success = function(data, status, objResponse){
                        if (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);
                    
                }
            }
        }
        
		/**
		 * Register help to popup in new windows
		 */
        var _registerHelpPop = function(){
        
            $('.help_pop').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 change market
		  */
		 var _registerLeftMarket = function(){
    
			 $('#leftMarketId').change(function(e){	

				 var strUrl = Arete.getUrl();
				 var arrUrlTokens = strUrl.split('#');

				 if ( arrUrlTokens.length > 1)
				 {
					 strUrl = arrUrlTokens[1];

					 strUrl = Arete.renameUrlParameter(strUrl, 'ajax-list', 'list');
					 strUrl = Arete.renameUrlParameter(strUrl, 'ajax-group-list', 'list');
				 }
				 
				 strUrl = Arete.removeUrlParameter(strUrl, 'page');
				 strUrl = Arete.removeUrlParameter(strUrl, 'groupBy');
				 strUrl = Arete.removeUrlParameter(strUrl, 'fId');
				 strUrl = Arete.removeUrlParameter(strUrl, 'fVal');
				 strUrl = Arete.removeUrlParameter(strUrl, 'incLive');
				 strUrl = Arete.removeUrlParameter(strUrl, 'excFlow');
				 strUrl = Arete.removeUrlParameter(strUrl, 'incLeverage');
				 
				 strUrl = Arete.removeUrlParameter(strUrl, 'rightIncLeverage');
				 strUrl = Arete.removeUrlParameter(strUrl, 'rightIncFlow');
				 
				 strUrl = Arete.addUrlParameter(strUrl, 'marketID', this.value, true);
				 strUrl = Arete.addUrlParameter(strUrl, 'changemarket', 1, true);

				 this.form.action = strUrl;
				 this.form.submit();
			 });
		 }
		  
		  /**
		  * Register user directory opt out tickbox change
		  */
		 var _registerUserDirectorytyOptOut = function(){

			 $('#userDirectoryOptIn').change(function(e){	

				 if ( this.checked)
				 {
					 //document.getElementById('userDirectoryName').disabled = false;
					 document.getElementById('userDirectoryCompany').disabled = false;
					 document.getElementById('userDirectoryPosition').disabled = false;
					 document.getElementById('userDirectoryCountry').disabled = false;
					 document.getElementById('userDirectoryCity').disabled = false;
					 document.getElementById('userDirectoryEmail').disabled = false;
					 document.getElementById('userDirectoryPhone').disabled = false; 
				 }
				 else
				 {
					 //document.getElementById('userDirectoryName').disabled = true;
					 document.getElementById('userDirectoryCompany').disabled = true;
					 document.getElementById('userDirectoryPosition').disabled = true;
					 document.getElementById('userDirectoryCountry').disabled = true;
					 document.getElementById('userDirectoryCity').disabled = true;
					 document.getElementById('userDirectoryEmail').disabled = true;
					 document.getElementById('userDirectoryPhone').disabled = true;
					 
					 //document.getElementById('userDirectoryName').checked = false;
					 document.getElementById('userDirectoryCompany').checked = false;
					 document.getElementById('userDirectoryPosition').checked = false;
					 document.getElementById('userDirectoryCountry').checked = false;
					 document.getElementById('userDirectoryCity').checked = false;
					 document.getElementById('userDirectoryEmail').checked = false;
					 document.getElementById('userDirectoryPhone').checked = false;
				 }
			 });
			 
			 $('#userDirectoryOptIn').change();
		 }		  
		  
		  /**
		  * Register quick search
		  */
		 var _registerQuickSearch = function(){
    
			$('#quickSearchForm').submit(function(e)
			{
				if (this.v_section_search[1].checked) // news search
				{
					this.action = '/news/news_list.php';
					this.method = 'get';					
				}
				else // product search
				{
					this.action = '/products/list/search' + '/keyword/' + encodeURI(this.keyword.value);
					this.method = 'post';
				}					
				
				this.submit();
			});
		 }
		 
        /**
         * Self executing init method
         */
        // Return the public properties and methods
         return {
             config: {
                 debug: false
             },
             log: function(mxdMsg){
                 if (this.config.debug === true) {
                     _log(mxdMsg)
                 }
             },
             clone: function(Super){
                 var clonedObject = {}
                 for (key in Super) {
                     if (Super.hasOwnProperty(key)) {
                         clonedObject[key] = Super[key];
                     }
                 }
                 return clonedObject;
             },
             logout: function(){
                 if (confirm("Are you sure you want to log out?\rYou will have to sign in again.")) 
                     window.location = "/logout.php";
             },
             init: function(){
                 _ajaxHack();
                 _registerHelpPop();
                 _registerLeftMarket();
                 _registerUserDirectorytyOptOut();
                 _registerQuickSearch();
				 _ieFixes();            
             },
             

             /**
       		  * Changes provided parameter in url depending on type:
       		  *  both - will remove parameter from both parts of url - normal and ajax
       		  *  normal - will remove parameter from the first part of url - normal
       		  *  ajax - will remove parameter from the second part of url - ajax
       		  *
         	  * @param string strUrlPath
         	  * @param string strParamName
         	  * @param string strNewValue
         	  * @param string strType both/normal/ajax
         	  * @return string
       		  */
       		  changeUrlParameter: function(strUrlPath, strParamName, strNewValue, strType)
       		  {
            	 if (typeof strType == "undefined")
      				  strType = 'both';
      			
        		  var arrPathTokens = strUrlPath.split('#');
        		  var arrOutput = [];
        		  var bolRemove = false; 
      		  
        		  if ( arrPathTokens.length > 1)
        		  {
        			  if ( strType === 'both')
        			  {
        				  $.each(arrPathTokens, function(index, value)
        				  {
        					  arrOutput.push( Arete._changeUrlParameter(value, strParamName, strNewValue));
        				  });
        			  }
        			  else if ( strType === 'ajax')
        			  {
        				 arrOutput.push( arrPathTokens[0]);
        				 arrOutput.push( Arete._changeUrlParameter(arrPathTokens[1], strParamName, strNewValue));
        			  }
        			  else
        			  {
        				 arrOutput.push( Arete._changeUrlParameter(arrPathTokens[0], strParamName, strNewValue));
        				 arrOutput.push( arrPathTokens[1]);
        			  }
        		  }
        		  else if ( strType === 'normal' || strType === 'both')
        		  {
        			 arrOutput.push( Arete._changeUrlParameter(arrPathTokens[0], strParamName, strNewValue));
        		  }
        		  else
        		  {
        			 arrOutput.push( arrPathTokens[0]);
        		  }

        		  return arrOutput.join('#');            	 
       		  },
       		  
              /**
               * Changes provided parameter in url
               * @param {Object} strUrlPath
               */
       		  _changeUrlParameter: function(strUrlPath, strParamName, strNewValue)
       		  {
          		  var arrPathTokens = strUrlPath.split('/');
          		  var arrOutput = [];
         		  var bolRemove = false;         		  
         		  $.each(arrPathTokens, function(index, value)
         		  {
         			  if (value === strParamName)         				  
         			  {
         				  bolRemove = true;
         				  arrOutput.push(strParamName);
         			  }
         			  else if ( bolRemove)
         			  {
         				 bolRemove = false;
         				 arrOutput.push(strNewValue);
         			  }
         			  else
         			  {
         				  bolRemove = false;
         				  arrOutput.push(value);
         			  }
         		  });

         		  return arrOutput.join('/');
       		  },
       		  
             /**
       		  * Remove provided parameter from url depending on type:
       		  *  both - will remove parameter from both parts of url - normal and ajax
       		  *  normal - will remove parameter from the first part of url - normal
       		  *  ajax - will remove parameter from the second part of url - ajax
       		  *
         	  * @param string strUrlPath
         	  * @param string strParamName
         	  * @param string strType both/normal/ajax
         	  * @return string
       		  */
       		  removeUrlParameter: function(strUrlPath, strParamName, strType)
       		  {
       			  if (typeof strType == "undefined")
       				  strType = 'both';
       			
         		  var arrPathTokens = strUrlPath.split('#');
         		  var arrOutput = [];
         		  var bolRemove = false; 
       		  
         		  if ( arrPathTokens.length > 1)
         		  {
         			  if ( strType === 'both')
         			  {
         				  $.each(arrPathTokens, function(index, value)
         				  {
         					  arrOutput.push( Arete._removeUrlParameter(value, strParamName));
         				  });
         			  }
         			  else if ( strType === 'ajax')
         			  {
         				 arrOutput.push( arrPathTokens[0]);
         				 arrOutput.push( Arete._removeUrlParameter(arrPathTokens[1], strParamName));
         			  }
         			  else
         			  {
         				 arrOutput.push( Arete._removeUrlParameter(arrPathTokens[0], strParamName));
         				 arrOutput.push( arrPathTokens[1]);
         			  }
         		  }
         		  else if ( strType === 'normal' || strType === 'both')
         		  {
         			 arrOutput.push( Arete._removeUrlParameter(arrPathTokens[0], strParamName));
         		  }
         		  else
         		  {
         			 arrOutput.push( arrPathTokens[0]);
         		  }

         		  return arrOutput.join('#');
       		  },
       		  
              /**
               * Remove provided parameter from url
               * @param string strUrlPath
               * @param string strParamName
               * @return string
               */
       		  _removeUrlParameter: function(strUrlPath, strParamName)
       		  {
          		  var arrPathTokens = strUrlPath.split('/');
          		  var arrOutput = [];
         		  var bolRemove = false;         		  
         		  $.each(arrPathTokens, function(index, value)
         		  {
        			  if (value === strParamName)
         				  bolRemove = true;
        			  else if ( bolRemove)
        				  bolRemove = false;
         			  else
         			  {
         				  bolRemove = false;
         				  arrOutput.push(value);
         			  }
         		  });

         		  return arrOutput.join('/');
       		  },
        		 
         	  /**
         	   * Add parameter to url
         	   * @param {Object} strUrlPath
         	   */
         	  addUrlParameter: function(strUrlPath, strParamName, strParamValue, bolReplace) 
         	  {
         		  if( bolReplace)
         			  strUrlPath = Arete.removeUrlParameter(strUrlPath, strParamName);
        		    	
         		  return strUrlPath + '/' + strParamName + '/' + strParamValue;
         	  },
         	  
         	 /**
         	   * Renames parameter in url
         	   * @param {Object} strUrlPath
         	   */
         	  renameUrlParameter: function(strUrlPath, strParamName, strNewParamName) 
         	  {  
         		  return strUrlPath.replace(strParamName, strNewParamName);
         	  },
        		        		
         	  /**
         	   * Gets url
         	   */
         	  getUrl: function() 
         	  {
         		  return location.href;	        
         	  }
        }
    })();
}
// Run the initlization
$().ready(function(){
	Arete.init();
});

