App = {

        Password: {
            'doPassStrength':function(obj,userID){
                obj.passStrength({
                    userid: userID
                })
            },
            
            'hasCriteria':function(){
                var min_length = 6;
                var num_uppercase = 0;
                var num_numeric = 1;
                var password = $('#password').val();

                var upper_case = 0;
                var numeric = 0;

               
                if( password.length >= min_length ){

                    /* Must meet number of uppercase*/
                    var match = password.match(/[A-Z]/);
                    if(match != null)
                        upper_case = match.length;

                    /* Must meet number of numeric */
                    match = password.match(/[0-9]/);
                    if( match != null )
                        numeric = match.length;

                    //alert('numeric: '+numeric+' || uppercase: '+upper_case);

                    if( upper_case < num_uppercase )
                        return false;

                    if( numeric < num_numeric)
                        return false;            

                    return true;

                }
                return false;
            },

            'gen':function() {
              var length = 6; 
              var numChars = '0123456789';
              var lowerChars = 'abcdefghijklmnopqrstuvwxyz';
              var upperChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';  
              var dontReplace = [];
              var iteration = 0;
              var password = "";

              while( iteration < length ){
                var thisPos = Math.floor(Math.random()* ( lowerChars.length - 1 ));
                var thisChar = lowerChars[ thisPos ];

                password += thisChar;
                iteration++;
              }

              where = App.Password.getRandom( length, dontReplace );
              dontReplace.push( where );
              number = numChars[  Math.floor( Math.random()* ( numChars.length - 1 )) ];
              password = password.replaceAt(where,number);

              log('numbers<br/>');
              log('where: '+where+' number:'+number+'<br/><br/>');
/*
              where = App.Password.getRandom( length, dontReplace );
              dontReplace.push( where );
              character = upperChars[  Math.floor(Math.random()* ( upperChars.length - 1 )) ];
              password = password.replaceAt(where,character);

              log('uppercase<br/>');
              log('where: '+where+' char:'+character);
*/
              return password;
            },

            "getRandom":function(max, except){

                var num = Math.floor(Math.random()* (max-1));

                var fail = false;

                $(except).each(function(){
                    if( this == num )
                        fail=true;
                })

                if(fail)
                    return App.Password.getRandom(max,except);

                return num;
            }


        },

        News:{
            'doPopups':function(){
                var popup;
                $('a.news_link').filter('.popup_link').click(function(e){
                    e.preventDefault();

                    popup = App.ModalDialog();
                    
                    popup.show(
                        'thisPopup',
                        'Leaving JamesFunds.com',
                        '<div class="closeOnClick">'+$('div.popup_text[rel="'+$(this).attr('rel')+'"]').html()+'</div>',
                        {width:500}
                    ); 
                });    
                $('div.closeOnClick a').live('click',function(){
                    popup.close();
                });
            },
            'doVideos':function(){
                var videopopup;
                $('a.video-link').click(function(e){
                    e.preventDefault();

                    videopopup = App.ModalDialog();
                    
                    var content = 'You are leaving the Jamesfunds website (jamesfunds.com). This link is provided for information purposes only and ALPS Distributors, Inc. is not responsible for the content beyond this point.<br/><br/>'+

                    'Please click the following link to continue:<br/><br/>'+
                    '<a href="'+ $(this).attr('href') +'" target="_blank" >'+ $(this).attr('href') +'</a>';
                    
                    
                    videopopup.show(
                        'thisPopup',
                        'Leaving JamesFunds.com',
                        '<div class="closeOnClick2">'+content+'</div>',
                        {width:500}
                    ); 
                });    
                $('div.closeOnClick2 a').live('click',function(){ 
                    videopopup.close();
                });    
                
            }
        },
	trackEvents: function(){ 
	
		/*
		 *	GET PAGE NAME
		 */
		var pos1 = document.location.href.lastIndexOf('/');
		//var where = document.location.href.substring(pos+1);
		var pos2 = document.location.href.lastIndexOf('.php');
		if(pos2>pos1){
			var where = document.location.href.substring(pos1+1,pos2) + '/';
		}else{
			var where = '';
		}

		/*
	     *	FACTSHEETS
		 
		$('a.trackFactsheet').click(function(e){
			e.preventDefault();
			alert(where +  this.name);
			_gaq.push(['_trackEvent', 'Factsheets', 'Download', where + this.name]);
		})
		*/
		
		/*
		 *	APPLICATIONS
		 * 	DOWNLOAD
		 */

		$('a.trackApplicationDown').click(function(e){
			_gaq.push(['_trackEvent', 'Applications', 'Download', where + this.name]);
		})
		
		
		/*
		 * 	APPLICATIONS
		 *	REQUEST A COPY
		 */
		 $('.request.trackApplication').click(function(){
			_gaq.push(['_trackEvent', 'Applications', 'Request A Copy', where+$(this).attr('href')]);
		 })
		 
		 
		 /*
		 *	APPLICATIONS
		 * 	Get Started online
		 */

		$('a.trackApplicationGetStarted').click(function(e){
			_gaq.push(['_trackEvent', 'Applications', 'Get Started', where + this.name]);
		})
		 
		 
		 /*
		 *	FORMS
		 *	DOWNLOAD
		 */
		$('a.trackFormDown').click(function(e){
			_gaq.push(['_trackEvent', 'Forms', 'Download', where + this.name]);
		})
		
		
		/*
		 *	FORMS
		 *	REQUEST A COPY
		 */
		 $('.request.trackForm').click(function(){
			_gaq.push(['_trackEvent', 'Forms', 'Request A Copy', where+$(this).attr('href')]);
		 })
		 
		 
		 /*
		 *	PROSPECTUS
		 *	VIEW
		 */
		$('a.trackProspectusView').click(function(e){
			_gaq.push(['_trackEvent', 'Prospectus', 'View', where + $(this).attr('name')]);
		})
		 
		 
		 
		 /*
		 *	PROSPECTUS
		 *	DOWNLOAD
		 */
		$('a.trackProspectusDown').click(function(e){
			_gaq.push(['_trackEvent', 'Prospectus', 'Download', where + $(this).attr('name')]);
		})
		
		
		/*
		 *	PROSPECTUS
		 *	REQUEST A COPY
		 */
		 $('.request.trackProspectus').click(function(){
			_gaq.push(['_trackEvent', 'Prospectus', 'Request A Copy', where+$(this).attr('name')]);
		 })
		 
		 
		 /*
		 *	REPORTS
		 *	DOWNLOAD
		 */
		$('a.trackReportView').click(function(e){
			_gaq.push(['_trackEvent', 'Annual Reports', 'View', where + $(this).attr('name')]);
		})
		 
		 
		 /*
		 *	REPORTS
		 *	DOWNLOAD
		 */
		$('a.trackReportDown').click(function(e){
			_gaq.push(['_trackEvent', 'Annual Reports', 'Download', where + this.name]);
		})
		
		
		/*
		 *	REPORTS
		 *	REQUEST A COPY
		 */
		 $('.request.trackReport').click(function(){
			_gaq.push(['_trackEvent', 'Annual Reports', 'Request A Copy', where+$(this).attr('href')]);
		 })
		 
		 
		 /*
		 *	REPORTS-SEMI
		 *	View
		 */
		$('a.trackReportSemiView').click(function(e){
			_gaq.push(['_trackEvent', 'Semi-Annual Reports', 'View', where + this.name]);
		})
		 
		 
		 
		 /*
		 *	REPORTS-SEMI
		 *	DOWNLOAD
		 */
		$('a.trackReportSemiDown').click(function(e){
			_gaq.push(['_trackEvent', 'Semi-Annual Reports', 'Download', where + this.name]);
		})
		
		
		/*
		 *	REPORTS-SEMI
		 *	REQUEST A COPY
		 */
		 $('.request.trackReportSemi').click(function(){
			_gaq.push(['_trackEvent', 'Semi-Annual', 'Request A Copy', where+$(this).attr('href')]);
		 })
		 
		 
		 
		 /*
		 *	SAI
		 *	VIEW
		 */
		 $('a.trackSAIView').click(function(){
			_gaq.push(['_trackEvent', 'SAI', 'View', where+$(this).attr('name')]);
		 })
		 
		 
		/*
		 *	SAI
		 *	REQUEST A COPY
		 */
		 $('.request.trackSAI').click(function(){
			_gaq.push(['_trackEvent', 'SAI', 'Request A Copy', where+$(this).attr('href')]);
		 })

                 /*
		 *	MORNINGSTAR
		 *	DOWNLOAD REPORT
		 */
		 $('a.trackAnalystReportDown').click(function(){
			_gaq.push(['_trackEvent', 'Morningstar Analyst Report', 'Download', where+$(this).attr('href')]);
		 })
                 /*
		 *	Undiscovered Managers
		 *	DOWNLOAD Article
		 */
		 $('a.trackUndiscoveredManagersDown').click(function(){
			_gaq.push(['_trackEvent', 'Undiscovered Managers Article', 'Download', where+$(this).attr('href')]);
		 })
	},

   /*
    *tabs
    *function to create james tabs
    *@param: params
    *expects JSON with:
    *start: { tab_id, content_id} //first tab shown onLoad
    *tabs:  [[tab_id, content_id}] //array of tab-content pairs
    *class_selected: class to apply when selected
    *class_default: class to apply when not selected
    */
   tabs: function(params){

       var start = params.start;
       var tabs = params.tabs; //tab_id, content_id
       var parent = $(params.start.tab_id).parent().attr('id');
       var class_selected = params.class_selected;
       var class_default = params.class_default;
       if(start!='undefined' && tabs !='undefined' && class_selected != 'undefined' && class_default != 'undefined' && parent != 'undefined'){
            $('#'+start.tab_id).removeClass(class_default).addClass(class_selected);
            $('#'+start.tab_id+' span').removeClass(class_default+'2').addClass(class_selected+'2')
            $('#'+start.content_id).show();
            $(tabs).each(function(){
                var thisObj = this;

                if( this.content_id != start.content_id){
                    $('#'+this.content_id).hide();
                    $('#'+this.tab_id).removeClass(class_selected).addClass(class_default);
                    $('#'+this.tab_id+' span').removeClass(class_selected+'2').addClass(class_default+'2')
                }

                $('#'+this.tab_id+' a').click(function(){
                    $(tabs).each(function(){
                        if( thisObj.content_id == this.content_id){
                            $('#'+this.content_id).show();
                            $('#'+thisObj.tab_id).removeClass(class_default).addClass(class_selected)
                            $('#'+thisObj.tab_id+' span').removeClass(class_default+'2').addClass(class_selected+'2')
                        }else{
                            $('#'+this.content_id).hide();
                            $('#'+this.tab_id).removeClass(class_selected).addClass(class_default);
                            $('#'+this.tab_id+' span').removeClass(class_selected+'2').addClass(class_default+'2')
                        }
                    })
                })
            })

       }else{
           //error
       }
   },

   ModalDialog: function() {

      /**
       * Current dialog reference
       *
       * @var jQuery
       */
      var dialog_object;

      // Let's return public interface object
      return {

        /**
         * Show modal dialog
         *
         *
         * @param String name
         * @param String title
         * @param mixed body
         * @param mixed settings
         */
        show : function(name, title, body, settings) {
          // dialog options
          var options = {
            modal     : true,
            draggable : false,
            resizable : true,
            title     : title,
            id        : name,
            position  : 'top',
            bgiframe  : true,
            close     : function (type,data) {
              if (settings.close) {
                settings.close();
              } // if
              dialog_object.dialog('destroy').remove();
            },
            resizeStart : function (type,data) {

            }
          };

          if (settings) {
            // width and height settings
            options.width = settings.width ? settings.width : 410;
            options.height = settings.height ? settings.height : 'auto';
            // additional buttons
            options.buttons = {};
            if (settings && settings.buttons) {
              for (var x = 0; x < settings.buttons.length; x++) {
                if (settings.buttons[x].callback) {
                  options.buttons[settings.buttons[x].label] = settings.buttons[x].callback;
                } else {
                  options.buttons[settings.buttons[x].label] = function () {
                    dialog_object.dialog('close');
                  } // function
                } // if
              } // if
            } // if
          } // if

          options.maxWidth = options.width;
          options.minWidth = options.width;
          //alert($(body).attr('class'));
          dialog_object = $(body).dialog(options);

          var counter = 0;
          dialog_object.parent().parent().find('.ui-dialog-buttonpane button').each(function () {
            var button = $(this);
            button.removeClass('ui-state-default').removeClass('ui-corner-all');

            var label = button.html();
            button.html('<span><span>' + label + '</span></span>');
            if (counter != 0) {
              button.addClass('alternative');
            } // if
            counter++;
          });
        },

        /**
         * Close the dialog
         */
        close : function() {
          dialog_object.dialog('destroy').remove();
        },

        /**
         * sets width of dialog
         */
        setWidth : function (width_px) {
          var dom_dialog = $('.ui-dialog');
          var position = dom_dialog.position();
          var new_left_offset = position.left - ((width_px - dom_dialog.width())/2);
          dom_dialog.css('width' , width_px+'px').css('left', new_left_offset+'px');
        },

        /**
         * Sets dialog title
         */
        setTitle : function (title) {
         var dom_dialog = $('.ui-dialog .ui-dialog-titlebar span.ui-dialog-title').html(title);
        },

        setBody: function (title) {
         var dom_dialog = $('.ui-dialog-content').html(title);
        },

        /**
         * Checks if dialog is open
         */
        isOpen : function () {
          if ($('.ui-dialog').length > 0) {
            return true;
          } else {
            return false;
          }
        }
      };

    },
    
    user_role: {
        show:function(){
            
            $.ajax({
                url:'/ajax/select_user_role.php',
                type:'GET',
                success:function(rslt){
                    $('#user_role_hidden').html(rslt);
                    $('#user_role_hidden').jqm({
                        modal:true,
                        onShow: function(h) {
                            h.w.fadeIn(); 
                        },
                        onHide: function(h){
                            h.w.fadeOut();  
                            h.o.fadeOut();
                        },
                        overlay:60
                    }).jqmShow();

                }
            })
            
        }
    }
}


String.prototype.replaceAt=function(index, chars) {

              var thing = this.substr(0, index) + chars + this.substr(index+1,this.length-1);
              log('<br/>replaced: '+thing+'<br/>');
              return thing;
           }
           
            function log(msg){
                return false;
                $('#debug').append(msg);
            }
           
           
/**
 * Modal dialog module
 */







function showHistoricalDiv(){
    //ModalDialog.show('historical','GLRBX Historical Asset Allocation',$('#GLRBXhistoricalDiv').html(),{width:620})
    $('#GLRBXhistoricalDiv').dialog({ //height: 500,
        width: 630,
        modal: true,
        position: 'top',
        title:'GLRBX Historical Asset Allocation.',
        overlay: { opacity: 0.5, background: 'black'}
    });
   // $('#GLRBX_historical_modal').load('/ajax/GLRBX_historical_nav_graph.php');
    return false;
}

$('.historical_asset_modal').live('click',function(){
    showHistoricalDiv();
})
$(document).ready(function(){
    $('.nightly_preview').click(function(e){
        e.preventDefault();
        var snapshot_url = "/ajax/nightly_snapshot.php";
        $.ajax({
            'url':snapshot_url,
            'type':"GET",
            'success':function(html){
                $(html).dialog({
                    width: 630,
                    modal: true,
                    position: 'top',
                    title:'Nightly NAV Email Snapshot',
                    overlay: { opacity: 0.5, background: 'black'}  ,
                    show: 'blind',
                    hide:'blind'
                })
            }
        })
        return false;
    })
    
    $('.advisor_alert_help').click(function(e){
        e.preventDefault();
        var html = '<div>When enabled, you will receive email notifications when the advisor logs into the system.</div>';
        $(html).dialog({
            width: 630,
            modal: true,
            position: 'top',
            title:'Advisor Alerts',
            overlay: { opacity: 0.5, background: 'black'}  ,
            show: 'blind',
            hide:'blind'
        })
        return false;
    })
})


//password generation
$.extend({   password: function (length, special) {    var iteration = 0;    var password = "";    var randomNumber;    if(special == undefined){        var special = false;    }    while(iteration < length){        randomNumber = (Math.floor((Math.random() * 100)) % 94) + 33;        if(!special){            if ((randomNumber >=33) && (randomNumber <=47)) { continue; }            if ((randomNumber >=58) && (randomNumber <=64)) { continue; }            if ((randomNumber >=91) && (randomNumber <=96)) { continue; }            if ((randomNumber >=123) && (randomNumber <=126)) { continue; }        }        iteration++;        password += String.fromCharCode(randomNumber);    }    return password;  }});

