(function (a) {
    a.fn.extend({
        charCounter: function (b) {
            return this.each(function () {
                var f = a(this),
                    e = a.extend({
                        maxChars: 100,
                        maxCharsWarning: 80,
                        msgFontSize: "11px",
                        msgFontColor: "gray",
                        msgTextAlign: "right",
                        msgWarningColor: "#F00",
                        msgAppendMethod: "insertAfter"
                    }, b);
                if (e.maxChars <= 0) {
                    return
                }
                var d = a('<div class="counterMsg">&nbsp;</div>');
                var c = {
                    "font-size": e.msgFontSize,
                    color: e.msgFontColor,
                    "text-align": e.msgTextAlign,
                    width: f.width(),
                    opacity: 0
                };
                d.css(c);
                d[e.msgAppendMethod](f);
                f.bind("keydown keyup keypress", g).bind("focus paste", function () {
                    setTimeout(g, 10)
                }).bind("blur", function () {
                    d.stop().fadeTo("fast", 0);
                    return false
                });

                function g() {
                    var i = f.val(),
                        h = i.length;
                    if (h >= e.maxChars) {
                        i = i.substring(0, e.maxChars)
                    }
                    if (h > e.maxChars) {
                        var j = f.scrollTop();
                        f.val(i.substring(0, e.maxChars));
                        f.scrollTop(j)
                    }
                    if (h >= e.maxCharsWarning) {
                        d.css({
                            color: e.msgWarningColor
                        })
                    } else {
                        d.css({
                            color: e.msgFontColor
                        })
                    }
                    d.html("Characters: " + f.val().length + "/" + e.maxChars);
                    d.stop().fadeTo("fast", 1)
                }
            })
        }
    })
})(jQuery);

var title;
var body;
var adType = 'sponsor';
function createUploader(){            
var uploader = new qq.FileUploader({
    element: $('#_image-preview')[0],
    action: baseUrl+'advertise/preview',
    debug: false,
    onSubmit: function(file, extension) {
    $('.preview-image').hide();
    $('.ajaxLoader').show();
    },
    onComplete: function(file, response) {
            $('.ajaxLoader').hide(); 
            var url = baseUrl+'uploads/'+response;
            $('.preview-image').attr('src',url);
            $('#imagePath').val(response);
            $('.preview-image').fadeIn();
    },
    onCancel: function() {
            $('.ajaxLoader').hide();	
    },
    multiple: false,
    fileTemplate: 
    '<li>' +
    '<span class="qq-upload-file"></span>' +
    '<span class="qq-upload-spinner"></span>' +
    '<span class="qq-upload-size"></span>' +
    '<a class="qq-upload-cancel" href="#">Cancel</a>' +
    '<span class="qq-upload-failed-text">Failed</span>' +
    '</li>'
    }); 
}

window.onload = createUploader; 

$(function(){
    
    /*
   * ADS STUFF
   * 
   * 
   */
   $('#loadCampaignList tr:even').css('background', '#efefef');
  
             function loadCampaignList(selector) {
                                    
                   $.post(baseUrl+'advertise/display/'+selector,{}, function(resp){
                       $('#loadCampaignList').html(resp); 
                       $('#loadCampaignList tr:even').css('background', '#efefef');
                   });
           }
//           
//           $('body').delegate('#sponsor, #feeds, #banner, #local_venues', 'click', function(e){
//               
//               $("#loadCampaignList").html('<img class="ajaxLoader" style="display: block; margin: 30px auto;" src="'+baseUrl+'includes/img/ajax_preloader.gif" width="64" height="64" />').fadeIn();
//               //e.preventDefault();
//               loadCampaignList($(this).attr('id'));              
//           });
  
    
    	$('.titleContent').charCounter({maxChars: 25, maxCharsWarning: 15});
	$('.descContent').charCounter({maxChars: 140, maxCharsWarning: 130});
	$('.sponsor').fadeIn();
	
	$('input[name=title]').keyup(function(e) {
		title = $(this).val();
		$('.preview-title-'+adType).text(title);
	});
	$('textarea[name=body]').keyup(function() {
		body = $(this).val();
		$('.preview-description-'+adType).text(body);
	});
	
	$('input[type=radio]').attr('disabled',false);
	
	$('input[name=type]').change(function() {
            
        $('input[type=text],textarea').val('');
        adType = $(this).attr('rel');
        $('dl[title=preview]').children('dd').hide();
        $('.'+adType).fadeIn();

        $('.titleContent, .descContent').unbind('keydown keyup keypress paste focus');
        $('.counterMsg').remove();

        $('input[name=title]').keyup(function(e) {
                title = $(this).val();
                $('.preview-title-'+adType).text(title);
        });

        $('textarea[name=body]').keyup(function() {
                body = $(this).val();
                $('.preview-description-'+adType).text(body);
        });

        var titleChars = {};
        var descChars = {};

        if(adType == 'sponsor') {

                titleChars.maxChars = 25;
                titleChars.maxCharsWarning = 15;
                descChars.maxChars = 140;
                descChars.maxCharsWarning = 130;
                
                $('.adTitle, .adBody, .adUrl').show();


        } else if(adType == 'feeds') {

                titleChars.maxChars = 65;
                titleChars.maxCharsWarning = 50;
                descChars.maxChars = 250;
                descChars.maxCharsWarning = 200;
                
                $('.adTitle, .adBody, .adUrl').show();

        } else if(adType == 'banner') {

                titleChars.maxChars = 75;
                titleChars.maxCharsWarning = 60;
                descChars.maxChars = 250;
                descChars.maxCharsWarning = 200;
                
                $('.adTitle, .adBody').hide();
                $('.adUrl').show();

        } else if(adType == 'local-venues') {

                titleChars.maxChars = 75;
                titleChars.maxCharsWarning = 60;
                descChars.maxChars = 250;
                descChars.maxCharsWarning = 200;
                
                $('.adTitle, .adBody').show();
                $('.adUrl').hide();        
        }

        $('.titleContent').charCounter({maxChars: titleChars.maxChars, maxCharsWarning: titleChars.maxCharsWarning});
        $('.descContent').charCounter({maxChars: descChars.maxChars, maxCharsWarning: descChars.maxCharsWarning});

    });
    /*
     * END OF ADS
     */
    
    
    
    
    /*==========================================================================
     * VALIDATION JS
     *
     */
    
    $('#frmAddChapter, #frmEditChapter').validate();
    
    $("#frmRegisterMember").validate({
    rules: {
        exp_date: "required",
        first_name: "required",
        last_name: "required",
        email_address: {
            required: true,
            email: true
        },
        email_address_confirm: {
            required: true,
            email: true,
            equalTo: "#email"
        },
        password: {
            required: true,
            minlength: 5
        },
        password_confirm: {
            required: true,
            minlength: 5,
            equalTo: "#password"
        },
        website: {
            url: true
        }
    },
    messages: {
        exp_date: "Please provide expiration date for account",
        firstname: "Please enter your firstname",
        lastname: "Please enter your lastname",
        password: {
            required: "Please provide a password",
            minlength: "Your password must be at least 5 characters long"
        },
        password_confirm: {
            required: "Please provide a password",
            minlength: "Your password must be at least 5 characters long",
            equalTo: "Please enter the same password as above"
        },
        email: "Please enter a valid email address",
        email_address_confirm: {
            required: "Please enter a valid email address",
            equalTo: "Please enter the same email as above"
        }
    }
}); 

  $("#frmRegisterPlace").validate({
    rules: {
        company: "required",
        company_address: "required",
        company_city: "required",
        company_state: "required",
        zip: "required",
        phone: "required",
        description: "required",
        hours_of_operation: "required",
        email_address: {
            required: true,
            email: true
        },
        website: {
            url: true
        }
    }
}); 
    
   
   /*===========================================================================
    * REGION JS
    */
   $('body').delegate('#addChapterRegion', 'click', function(e){
       
       e.preventDefault();
       
       var city = $(this).parent().find('.txtCity').val();
       var state = $(this).parent().find('.txtState').val();
       
       if(city !== '' || state !== '') {
           
           $('#loadChaptersRegions').html('<li><img class="ajaxLoader" style="display: block; margin: 10px auto 0;" src="'+baseUrl+'includes/img/spinner.gif" width="24" height="24" /> Getting list of regions...</li>');
           
            $.post(baseUrl+'admin/manage_chapter_regions/add', {'city' : city, 'state' : state, 'offset' : $('#offset').val()}, function(resp){
            
                $('#loadChaptersRegions').html(resp);
                
            });
           
       } else {
            alert('Both fields are required.');
       }
   });
   
   $('body').delegate('#editChapterRegion', 'click', function(e){
       
       e.preventDefault();
       
       var city = $(this).parent().find('.txtCity').val();
       var state = $(this).parent().find('.txtState').val();
       var regionId = $(this).parent().parent().find('input:hidden').val();
       
       if(city !== '' || state !== '') {
           
           $('#loadChaptersRegions').html('<li><img class="ajaxLoader" style="display: block; margin: 10px auto 0;" src="'+baseUrl+'includes/img/spinner.gif" width="24" height="24" /> Getting list of regions...</li>');
           
            $.post(baseUrl+'admin/manage_chapter_regions/update', {'region_id' : regionId,'city' : city, 'state' : state, 'offset' : $('#offset').val()}, function(resp){
            
                $('#loadChaptersRegions').html(resp);
                
            });
           
       } else {
            alert('Both fields are required.');
       }
   });
   
   $('body').delegate('.deleteRegion', 'click', function(e){
       
       e.preventDefault();
       
       var regionId = $(this).parent().find('input:hidden').val();
       
       if(confirm('Are you sure that you want to delete this region?')) {
           $('#loadChaptersRegions').html('<li><img class="ajaxLoader" style="display: block; margin: 10px auto 0;" src="'+baseUrl+'includes/img/spinner.gif" width="24" height="24" /> Getting list of regions...</li>');

            $.post(baseUrl+'admin/manage_chapter_regions/delete', {'region_id' : regionId, 'offset' : $('#offset').val()}, function(resp){

                $('#loadChaptersRegions').html(resp);

            });
       } else {
           return;
       }
           
   });
   
    $('body').delegate('.editRegion', 'click', function(){
       
       $(this).parent().find('.editRegionBox').toggle();
           
   });
   
   /*===========================================================================
    *CHAPTER JS
    * 
    */
   
   $('body').delegate('.deleteChapter', 'click', function(e){
       
       e.preventDefault();
       
       var chapterId = $(this).parent().find('input[name=chapter_id]').val();
       
       if(confirm('Are you sure that you want to delete this chapter?')) {
           $('#loadChapters').html('<li><img class="ajaxLoader" style="display: block; margin: 10px auto 0;" src="'+baseUrl+'includes/img/spinner.gif" width="24" height="24" /> Getting list of regions...</li>');

            $.post(baseUrl+'admin/manage_chapters/delete', {'chapter_id' : chapterId, 'offset' : $('#offset').val()}, function(resp){

                $('#loadChapters').html(resp);

            });
       } else {
           return;
       }
           
   });
    
      

   
   $('body').delegate('.editDetails', 'click', function(){
      
      if($('.edit-input').is(':visible')) {
          
          $('.edit-input').hide();
          $('.preview-value').show();
     
      } else {
          $('.edit-input').show();
          $('.preview-value').hide();
      }      
   });
   
   
      $('body').delegate('#btnUpdateChapter', 'click', function(e){
       
       e.preventDefault();
       
       var data = $('#frmEditChapter').serialize();
       
       $('#frmEditChapter').html('<img class="ajaxLoader" style="display: block; margin: 10px auto 0;" src="'+baseUrl+'includes/img/spinner.gif" width="24" height="24" /> Saving data...');

        $.post(baseUrl+'admin/manage_chapters/update', data, function(resp){

            $('#frmEditChapter').html(resp);

        });
           
   });
   
    /*===========================================================================
    * INDUSTRIES JS
    */
   $('body').delegate('#addIndustry', 'click', function(e){
       
       e.preventDefault();
       
       var name = $(this).parent().find('.txtIndustry').val();
       
       if(name !== '') {
           
           $('#loadIndustries').html('<li><img class="ajaxLoader" style="display: block; margin: 10px auto 0;" src="'+baseUrl+'includes/img/spinner.gif" width="24" height="24" /> Getting list of regions...</li>');
           
            $.post(baseUrl+'admin/manage_industries/add', {'name' : name, 'offset' : $('#offset').val()}, function(resp){
            
                $('#loadIndustries').html(resp);
                
            });
           
       } else {
            alert('The name field is required.');
       }
   });
   
   $('body').delegate('#editIndustry', 'click', function(e){
       
       e.preventDefault();
       
       var name = $(this).parent().find('.txtIndustry').val();
       var industryId = $(this).parent().parent().find('input:hidden').val();
       
       if(name !== '') {
           
           $('#loadIndustries').html('<li><img class="ajaxLoader" style="display: block; margin: 10px auto 0;" src="'+baseUrl+'includes/img/spinner.gif" width="24" height="24" /> Getting list of regions...</li>');
           
            $.post(baseUrl+'admin/manage_industries/update', {'industry_id' : industryId,'name' : name, 'offset' : $('#offset').val()}, function(resp){
            
                $('#loadIndustries').html(resp);
                
            });
           
       } else {
            alert('The name field is required.');
       }
   });
   
   $('body').delegate('.deleteIndustry', 'click', function(e){
       
       e.preventDefault();
       
       var industryId = $(this).parent().find('input:hidden').val();
       
       if(confirm('Are you sure that you want to delete this region?')) {
           $('#loadIndustries').html('<li><img class="ajaxLoader" style="display: block; margin: 10px auto 0;" src="'+baseUrl+'includes/img/spinner.gif" width="24" height="24" /> Getting list of regions...</li>');

            $.post(baseUrl+'admin/manage_industries/delete', {'industry_id' : industryId, 'offset' : $('#offset').val()}, function(resp){

                $('#loadIndustries').html(resp);

            });
       } else {
           return;
       }
           
   });
   
   $('body').delegate('.editIndustry', 'click', function(){
       
       $(this).parent().find('.editIndustryBox').toggle();
           
   });
   
   /*===========================================================================
    *CHAPTER JS
    * 
    */
   
   $('body').delegate('.deleteMember', 'click', function(e){
       
       e.preventDefault();
       
       var memberId = $(this).parent().find('input[name=member_id]').val();
       
       if(confirm('Are you sure that you want to delete this member?')) {
           $('#loadMembers').html('<li><img class="ajaxLoader" style="display: block; margin: 10px auto 0;" src="'+baseUrl+'includes/img/spinner.gif" width="24" height="24" /> Getting list of members...</li>');

            $.post(baseUrl+'admin/manage_members/delete', {'member_id' : memberId, 'offset' : $('#offset').val()}, function(resp){

                $('#loadMembers').html(resp);

            });
       } else {
           return;
       }
           
   });
   $('body').delegate('.deletePlace', 'click', function(e){
       
       e.preventDefault();
       
       var placeId = $(this).parent().find('input[name=id]').val();
       
       if(confirm('Are you sure that you want to delete this member?')) {
           $('#loadMembers').html('<li><img class="ajaxLoader" style="display: block; margin: 10px auto 0;" src="'+baseUrl+'includes/img/spinner.gif" width="24" height="24" /> Getting list of members...</li>');

            $.post(baseUrl+'admin/manage_eat_meet/delete', {'id' : placeId, 'offset' : $('#offset').val()}, function(resp){

                $('#loadMembers').html(resp);

            });
       } else {
           return;
       }
           
   });
   
   
    $('body').delegate('#btnAddToHitList', 'click', function(e){
       
        e.preventDefault();
        
        if($('#loadHitList li').size() < 5) {
         
            var data = $(this).parent().serialize();
            var url = $(this).parent().attr('action');

            $('#loadHitList').html('<li><img class="ajaxLoader" style="display: block; margin: 10px auto 0;" src="'+baseUrl+'includes/img/spinner.gif" width="24" height="24" /> Getting Hit List...</li>');

            $.post(url, data, function(resp){

                $('#loadHitList').html(resp);

            });
        } else {
            alert('You can add up to max of five categories.');
        }          
    });
    
    
    $('body').delegate('#btnRemoveFromHitList', 'click', function(e){
       
        e.preventDefault();
       
        var data = $(this).parent().serialize();
        var url = $(this).parent().attr('action');
        
        if(confirm('Are you sure that you want to delete this item?')) {

            $('#loadHitList').html('<li><img class="ajaxLoader" style="display: block; margin: 10px auto 0;" src="'+baseUrl+'includes/img/spinner.gif" width="24" height="24" /> Getting Hit List...</li>');

            $.post(url, data, function(resp){

                $('#loadHitList').html(resp);

            });
        } else {
            return;
        }
           
    });
    
    
    $('.uiButton').button();
    $('#datepicker').datepicker();
    $('.icon, .ui-icon, .upload-logo, .upload-video, .deleteMember').tipsy();
   $('.icon').css({backgroundPosition: '0 0'});
      $('.icon').hover(function(){
		$(this).animate({
			backgroundPosition: '0 -150px'
		},500) 
    }, function(){
		$(this).animate({
			backgroundPosition: '0 0'
		},500);
    });
    
    
     $('body').delegate('#addMemberIndustry', 'click', function(){
          
          var text = $("#industry option:selected").text(), value = $("#industry option:selected").val();
          
          if($('.industry-item').length < 3) {
              
              var html =  '<div class="industry-item">';
                  html += '<div class="industry-name">'+text+'<span class="deleteMemberIndustry">Remove</span></div>';
                  html += '<input type="hidden" value="'+value+'" name="industry[]" />';
                  
                  $('.industries-form-wrapper').append(html);
              
          } else {
              alert('You can add up to 3 Industries.')
          }
          
       });
       
       $('body').delegate('.deleteMemberIndustry','click', function(){
            
            $(this).parent().parent().remove();
       
       });
    
    
   // $('.icon')
	// .mouseover(function(){
		// $(this).stop().animate(
			// {backgroundPosition:"0 -200px"}, 
			// {duration:500})
		// })
	// .mouseout(function(){
		// $(this).stop().animate(
			// {backgroundPosition:"0 0"}, 
			// {duration:500})
		// });
   
});
