﻿

var previewMode=0;
var removeBaseImage= true;
var currentcarousel = null;
var currentThumbID  = null;
var arrayPic  = [];

var searchPage = "chooseAmember.aspx";


var baseImagePath = '/Resources/Images/sponsor/groupPhotoPlaceholder.gif';


jQuery.fn.extend({
	everyTime: function(interval, label, fn, times, belay) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, times, belay);
		});
	},
	oneTime: function(interval, label, fn) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, 1);
		});
	},
	stopTime: function(label, fn) {
		return this.each(function() {
			jQuery.timer.remove(this, label, fn);
		});
	}
});

jQuery.extend({
	timer: {
		guid: 1,
		global: {},
		regex: /^([0-9]+)\s*(.*s)?$/,
		powers: {
			// Yeah this is major overkill...
			'ms': 1,
			'cs': 10,
			'ds': 100,
			's': 1000,
			'das': 10000,
			'hs': 100000,
			'ks': 1000000
		},
		timeParse: function(value) {
			if (value == undefined || value == null)
				return null;
			var result = this.regex.exec(jQuery.trim(value.toString()));
			if (result[2]) {
				var num = parseInt(result[1], 10);
				var mult = this.powers[result[2]] || 1;
				return num * mult;
			} else {
				return value;
			}
		},
		add: function(element, interval, label, fn, times, belay) {
			var counter = 0;
			
			if (jQuery.isFunction(label)) {
				if (!times) 
					times = fn;
				fn = label;
				label = interval;
			}
			
			interval = jQuery.timer.timeParse(interval);

			if (typeof interval != 'number' || isNaN(interval) || interval <= 0)
				return;

			if (times && times.constructor != Number) {
				belay = !!times;
				times = 0;
			}
			
			times = times || 0;
			belay = belay || false;
			
			if (!element.$timers) 
				element.$timers = {};
			
			if (!element.$timers[label])
				element.$timers[label] = {};
			
			fn.$timerID = fn.$timerID || this.guid++;
			
			var handler = function() {
				if (belay && this.inProgress) 
					return;
				this.inProgress = true;
				if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
					jQuery.timer.remove(element, label, fn);
				this.inProgress = false;
			};
			
			handler.$timerID = fn.$timerID;
			
			if (!element.$timers[label][fn.$timerID]) 
				element.$timers[label][fn.$timerID] = window.setInterval(handler,interval);
			
			if ( !this.global[label] )
				this.global[label] = [];
			this.global[label].push( element );
			
		},
		remove: function(element, label, fn) {
			var timers = element.$timers, ret;
			
			if ( timers ) {
				
				if (!label) {
					for ( label in timers )
						this.remove(element, label, fn);
				} else if ( timers[label] ) {
					if ( fn ) {
						if ( fn.$timerID ) {
							window.clearInterval(timers[label][fn.$timerID]);
							delete timers[label][fn.$timerID];
						}
					} else {
						for ( var fn in timers[label] ) {
							window.clearInterval(timers[label][fn]);
							delete timers[label][fn];
						}
					}
					
					for ( ret in timers[label] ) break;
					if ( !ret ) {
						ret = null;
						delete timers[label];
					}
				}
				
				for ( ret in timers ) break;
				if ( !ret ) 
					element.$timers = null;
			}
		}
	}
});

if (jQuery.browser.msie)
	jQuery(window).one("unload", function() {
		var global = jQuery.timer.global;
		for ( var label in global ) {
			var els = global[label], i = els.length;
			while ( --i )
				jQuery.timer.remove(els[i], label);
		}
	});




(function($) {

    $.fn.charCount = function(options) {
  
        // default configuration properties
        var defaults = {
            allowed: 2500
        };
        
        var options = $.extend(defaults, options);
        function calculate(obj) {
      
            var count = $(obj).val().length;
       
            if (count > options.allowed) {
                var substringValue = $(obj).val()
                substringValue = substringValue.substr(0, options.allowed)
                $(obj).val(substringValue)
             
              count = $(obj).val().length;
            }        
           
            if ($(obj).next().find(".chgNum")[0]) 
            {
           
                $(obj).next().find(".chgNum").html(count);
            } 
            else 
            {                
               $(obj).parent().find(".chgNum").html(count);               
            }            
        };
        this.each(function() {
            calculate(this);
            $(this).keyup(function() { calculate(this) });
            $(this).change(function() { calculate(this) });
        });
    };
})(jQuery);
 
 
function addImageUrl(p_url,p_cover)
{
    var ii= new Object;

    ii.url =p_url;
    ii.iscover = p_cover;
    arrayPic.push(ii)
}

function removeImageUrlArray(p_url)
{

    for(i=0; i< arrayPic.length; i++) 
            { 
                if(arrayPic[i].url == p_url)
                {
                    arrayPic.splice(i,1);
                }
                
            }
}
 

function participantSeach(page)
{
    var options = {
        type: "POST",
        url: "/" + searchPage + "/searchResult",
        data: "{searchType:'" + $('.ddSearchType').val() +"',search:'" + $('.TextBoxSearch').val() + "',page:" + page + ",preview_qs:'" + $('.preview_qs').html() + "',isDonation:'" + $('.donation').html() + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) 
        {
           $('.resultBloc').html(msg.d);
        }
    };
    $.ajax(options);
} 

function bindParticipantSearch()
{

    $('.searchParticipant').click(function()
    {
        participantSeach(0);
    });
    
    $('.TextBoxSearch').focus(function()
    {
        if( $(this).val() == "Search for a Member")
        {
            $(this).val("");
        }
    });
    $('.pageLink').live('click',function()
    {
        participantSeach($(this).attr("page"));
        return false;
    });
    
    $('.pageLinkCurrent').live('click',function()
    {
        return false;
    });
    
    $('.previousPage').live('click',function()
    {
        var cp = $('.currentPage').html();        
        participantSeach(--cp);
        return false;
    });
    
    
    $('.nextPage').live('click',function()
    {
        var cp = $('.currentPage').html();        
        participantSeach(++cp);
        return false;
    });
    
     $('.searchParticipant').trigger('click');
     
     $('.ddSearchType').change(function()
     {
         $('.searchParticipant').trigger('click');
     });
}


function mycarousel_itemLoadCallback(carousel, state)
{
   
    for (var i = carousel.first; i <= carousel.last; i++) {
        if (carousel.has(i)) {
            continue;
        }
        
        if (i > arrayPic.length) {
            break;
        }
       
        carousel.add(i, mycarousel_getItemHTML(arrayPic[i-1].url, arrayPic[i-1].iscover));
    }
     currentcarousel  = carousel;
};


function mycarousel_getItemHTML(url, iscover)
{
    return '<div class="displayImage" IsCoverAlbum="' + iscover + '" thumbid="' + url + '"><img src="' + url + '"  alt="' + url + '" /></div>';
};


function carousel_callback( carousel, state) 
{
    currentcarousel  = carousel;
}


function removeUrl(url)
{
    $.ajax({
        url: '/Components/User/PictureGallery/ajax.aspx',
        dataType : 'text',
        data: "removeUrl=" + url,
        success: function(data) 
        {
            
        }
        });
}

function removeIsCoverAttr()
{
  $('.displayImage').each(function(index) 
    {
      $(this).attr('IsCoverAlbum','0');  
    });
}

function bindImageDisplay()
{    
    $('.jqSetCoverAlbum').click(function()
    {    
       removeIsCoverAttr();
        
       $("div[thumbid='" + currentThumbID + "']").attr('IsCoverAlbum','1');
       $('.jqSetCoverAlbum').css('visibility','hidden');
       $('.jqSetCoverAlbum').css('display','none');
       
       $('.jqThisIsCoverAlbum').css('visibility','visible');
       $('.jqThisIsCoverAlbum').css('display','block');
 
         for(i=0; i< arrayPic.length; i++) 
            { 
                arrayPic[i].iscover = 0;
                if(arrayPic[i].url == currentThumbID)
                {
                    arrayPic[i].iscover = 1;    
                }
            }
 
 
      $.ajax({
        url: '/Components/User/PictureGallery/ajax.aspx',
        dataType : 'text',
        data: "setCoverUrl=" +   currentThumbID ,
        success: function(data) {}});  
        return false;
    });
    
    $('.jqDeleteImageJULY2010').live('click',function()
    {       
        if( currentcarousel != null)
        {
           
            
            
            //decrease totallabel       
            var total = $(".pictureCount").html();
            total--;        
            $(".pictureCount").html(total);
            
            CurrentMaxImage++;        
            removeImageUrlArray(currentThumbID);

            $('#masterC').html("");
            $('#mycarousel').remove();            
            $("#masterC").append('<ul id="mycarousel" class="jcarousel-skin-tango" ></ul>');
            jQuery('#mycarousel').jcarousel({size: arrayPic.length,itemLoadCallback: {onBeforeAnimation: mycarousel_itemLoadCallback}});

      
            removeUrl( currentThumbID )
            currentThumbID= null;
         
           if(total == 0)
           {
                addCarrouselImage(baseImagePath);
                removeBaseImage = true;
                CurrentMaxImage++;
           }  
           
           $('#mycarousel').find('div:eq(0)').trigger('click'); 
            $('#fileInput').uploadifySettings('queueSizeLimit',CurrentMaxImage); 
            
            
        }
        else
        {
            removeUrl(  $('.profileImage').attr('src') );
            changeCurrentImage(baseImagePath);
            $('.jqDeleteImageJULY2010').css('visibility','hidden');
        
        }          
      return false;
    });    
    
    $('.jqSavePictureJuly2010').live('click',function()
    {
        $('.imageCheckJuly2010').each(function(index) 
        {
       
            if( CurrentMaxImage > 0)
            {
                if($(this).is(':checked'))
                {           
                    addCarrouselImage( $(this).attr("pic"));
                }
            }
        });

        $('#cboxClose').trigger('click');
        return false;
    });
    
    $('.photoGallery').colorbox( {title:"Select an image to add it to your photo gallery",width:"1000px", height:"999px"});
    
    $('.colorBoxForgetPass').colorbox( {width:"650px", height:"360px", scrolling:false, iframe:true});
    
    $('.rightCol .preview .thumb').colorbox({width:"861px", height:"999px"});
    $('.rightCol .preview .poplink').colorbox({width:"861px", height:"999px"});
    
    $('.displayImage').live('click',function()
     {            
        if( currentThumbID != null)
        {
             $("div[thumbid='" + currentThumbID + "']").css('border-style','none');
             $('.jqDeleteImageJULY2010').css('visibility','visible');
        }
     
        currentThumbID = $(this).attr("thumbid");
        iscoveralbum   = $(this).attr("IsCoverAlbum");        
        nameContext    = $(this).attr("nameContext");
        target         = $(this).attr("target");
        
        if( currentThumbID != baseImagePath )
        {
            removeBaseImage= false;
        }
        
        supportURL = $(this).attr("supportURL");
        supportTXT = $(this).attr("supportTXT");
        
        if(previewMode != 1)
        {
            SetImageLink($(this).attr("imageID"));
        }
        
        $('.supportBtnPhotoLink').html(supportTXT);
        $('.supportBtnPhotoLink').attr('href',supportURL);
        if (target != "")
            $('.supportBtnPhotoLink').attr('target',target);
        else
            $('.supportBtnPhotoLink').removeAttr('target');
        $('.pictureLabel').html(nameContext);       
        
       
        if(iscoveralbum =="1" || iscoveralbum =="true" )
        {
            $('.jqSetCoverAlbum').css('visibility','hidden');
            $('.jqSetCoverAlbum').css('display','none');
            
            $('.jqThisIsCoverAlbum').css('visibility','visible');
            $('.jqThisIsCoverAlbum').css('display','block');            
        }
        else
        {
            $('.jqSetCoverAlbum').css('visibility','visible');
            $('.jqSetCoverAlbum').css('display','block');
            
            $('.jqThisIsCoverAlbum').css('visibility','hidden');
            $('.jqThisIsCoverAlbum').css('display','block');
        }
        
         $(this).css('border-style','dashed'); 
         $(this).css('border','1px solid #c4d2e0'); 
        
         var a= $(this).children()[0];
         var pathimage = $(a).attr("src");
         
        $('.profileImage').attr("src", pathimage);      
     });
        
    $('.displayImage').mouseover( MouseOverPicture );
    
    $('div[IsCoverAlbum="1"]').trigger('click');  
}

function SetImageLink(p_imageID)
{
    if (p_imageID < 0) return;
    $('.linkImageParam').each(function(index) {
        var urlobj = jQuery.url.setUrl($(this).attr("href"));
        var path = urlobj.attr("path");
        var query = urlobj.attr("query");
        if (query == null)
            query = '';
        
        if (query.indexOf("imageID=") == -1)
            $(this).attr("href", path + "?imageID=" + p_imageID + (query == '' ? '' : "&" + query));
        else
            $(this).attr("href", path + "?" + query.replace(jQuery.url.param("imageID"), p_imageID));
    });
}

function MouseOverPicture()
{
    if(currentThumbID != $(this).attr("thumbid"))
    {
        $(this).css('border','1px solid #c4d2e0'); 
        $(this).mouseout(function()
        { 
            if(currentThumbID != $(this).attr("thumbid"))
            {
                $(this).css('border-style','none'); }
            }
        ); 
    }
}


function replaceall(txt, pcFrom, pcTo)
{

var i = txt.indexOf(pcFrom);

var c = txt;

while (i > -1){

c = c.replace(pcFrom, pcTo);

i = c.indexOf(pcFrom);

}

return c;

}

function bindBackToOriginalText()
{
    $('.func_backToOriginal').click(function()
    {    
       
       var fromTxtID = $(this).attr('from');
       var toTxtID = $(this).attr('to');
       
        //BR are not render the same way at the end on every browser
        var noriginalTxt = replaceall( $("#" + fromTxtID).html(),"<br>","\r\n"); 
        noriginalTxt= replaceall( noriginalTxt,"<BR>","\r\n"); 
        noriginalTxt= replaceall( noriginalTxt,"<BR/>","\r\n"); 
        noriginalTxt= replaceall( noriginalTxt,"<BR />","\r\n"); 
        noriginalTxt= replaceall( noriginalTxt,"<br/>","\r\n"); 
        noriginalTxt= replaceall( noriginalTxt,"<br />","\r\n"); 
        
       $("#" + toTxtID ).val(  noriginalTxt);
       return false;
    });

    
   
    $('.TargetText2500').charCount({ allowed: 2500 });

    
}

function bindWebAddress()
{



    $('.jqValideWebAddressJULY2010').click(function()
    {   
        $.ajax({
        url: '/Components/User/webAddress/ajaxcall.aspx',
        dataType : 'text',
        data: "validewebaddress=" + $('.currentSelectionJULY2010').val() + "&webaddresstype=" + webaddresstype + "&sponsorredirect=" + $('.sponsorredirect').html(),
        success: function(data) 
        {
            if(data == "1") { webAddressAvailable()}
            else { webAddressNotAvailable()}
        }
        });
        return false;
    });    
    
    $('.jqBackToOriginalSuggestionJULY2010').click(function()
    {
       $('.currentSelectionJULY2010').val($('.OriginalSelectionJULY2010').html());       
        webAddressAvailable();
        $('.jqBackToOriginalSuggestionJULY2010').css('visibility','hidden');
    });    
    
     $('.currentSelectionJULY2010').keydown(function(event)
     {
        $('.jqValideWebAddressJULY2010').css('visibility','visible');
        $('.jqValideWebAddressJULY2010').css('display','block');
        
        $('.notavailableJULY2010').css('visibility','hidden');
        $('.notavailableJULY2010').css('display','none');
        
        $('.isavailableJULY2010').css('visibility','hidden');
        $('.isavailableJULY2010').css('display','none');
     });   
}

function webAddressAvailable()
{
    $('.isavailableJULY2010').css('visibility','visible');
    $('.isavailableJULY2010').css('display','block');
    
    $('.notavailableJULY2010').css('visibility','hidden');
    $('.notavailableJULY2010').css('display','none');
    
    $('.jqBackToOriginalSuggestionJULY2010').css('visibility','hidden');
    $('.jqBackToOriginalSuggestionJULY2010').css('display','none');
    
    $('.jqValideWebAddressJULY2010').css('visibility','hidden');
    $('.jqValideWebAddressJULY2010').css('display','none');    
}

function webAddressNotAvailable()
{
    $('.notavailableJULY2010').css('visibility','visible');
    $('.notavailableJULY2010').css('display','block');
    
    $('.jqBackToOriginalSuggestionJULY2010').css('visibility','visible');
    $('.jqBackToOriginalSuggestionJULY2010').css('display','block');
    
    $('.isavailableJULY2010').css('visibility','hidden');
    $('.isavailableJULY2010').css('display','none');
    
    $('.jqValideWebAddressJULY2010').css('visibility','hidden');
    $('.jqValideWebAddressJULY2010').css('display','none');
}

function renderToolTip()
{
    $("a[titletip]").tooltip({

		// use div.tooltip as our tooltip
		tip: '.tooltip',

		// use the fade effect instead of the default
		effect: 'toggle',

		// make fadeOutSpeed similar to the browser's default
		fadeOutSpeed: 100,

		// the time before the tooltip is shown
		predelay: 0,

		// tweak the position
		position: "top right",
		offset: [+15, +5]
	}); 
	
	
	$("#tiprule").tooltip({

		// use div.tooltip as our tooltip
		tip: '.tooltipRules',

		// use the fade effect instead of the default
		effect: 'toggle',

		// make fadeOutSpeed similar to the browser's default
		fadeOutSpeed: 100,

		// the time before the tooltip is shown
		predelay: 0,

		// tweak the position
		position: "bottum",
		offset: [+15, +5]
	}); 
	
     $(".tooltipFade").fadeIn(3500);
     
     $(".tooltipFade").oneTime(10000, "hide", function() 
      {
        $(".tooltipFade").fadeOut(15500);
      });

}

function bindRegistration() {

    
    $('#groupOrIndividual .groupcontent .subpage').colorbox({width:"861px", height:"999px"});
    $('.esubs_terms').colorbox({width:"82%", height:"100%", scrolling:true, iframe:true});
    $('.esubs_privacy_policy').colorbox({width:"900px", scrolling:false});
    
    //$('#cboxTitle').css("top","-500px"); 
    //$('#cboxLoadedContent').css("margin","0");

    // Terms and Condition checkbox will toggle the Continue button in Sponsor & Participant Step 1 registration
    /*
    $("input[name*='TermsCheckBox']").live('click', function() {
        // if the BlockUnder13 warning is there we block the button continue
        if ($('.BlockUnder13')[0]) {
            return;
        }
        
        var continuebtn = $('.mainContentBloc .continue').children()[0];
        if ($(this).is(':checked'))
            $(continuebtn).attr("disabled", false).attr("src", "/Resources/Images/sponsor/continueBtn.gif");
        else
            $(continuebtn).attr("disabled", true).attr("src", "/Resources/Images/sponsor/continueBtn_grey.gif");
    });   
    */
    
    
    /* If page does postback and the terms is checked already, remove the disabled style from Continue button */
    var termsChk = $("input[name*='TermsCheckBox']");
    if ($(termsChk).is(':checked')) 
    {
        // if the BlockUnder13 warning is there we block the button continue
        if( $('.BlockUnder13')[0])
        {
            return;
        }
       
        var continuebtn = $('.mainContentBloc .continue').children()[0];  
        $(continuebtn).attr("disabled", false).attr("src","/Resources/Images/sponsor/continueBtn.gif");
    }

    $('.EventDateYes').click(function() {

       $('.pickerBloc').css('visibility', 'visible');

   });

   $('.EventDateNo').click(function() {

       $('.pickerBloc').css('visibility', 'hidden');

   });

    $('.IndividualRadioButton').click(function() {

        $('.blocGroupMember').css('visibility', 'hidden');

    });

    $('.GroupRadioButton').click(function() {

        $('.blocGroupMember').css('visibility', 'visible');

    });

    $('.bContinueWizard').click(function() {

        var termsChk = $("input[name*='TermsCheckBox']");
        if ($(termsChk).is(':checked')) {

            return true;
        }
        else 
        {
            if ($('.joinCampaign').length)
                alert('You need to have read and agreed to the Terms of Service before you can Continue.');
            else
                return true;
        }
        
        return false;

    });


    
    
}

function bindCampaignManager()
{
    // Bind the Preview on CMEditSite.aspx
    $('.PreviewLink').colorbox({width:"1000px", height:"900px", scrolling:false, iframe:true});
    $('.PreviewCMEditSite').live('click',function()
    {
         var options = {
            type: "POST",
            url: "/CMEditSite.aspx/ShowGroupPagePreview",
            data: "{supportOurCauseText:\"" + $('.TargetText').val() + "\",fundraisingGoal:'" + $('.CampaignGoal').val() + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) 
            {
               $('.PreviewLink').attr("href", msg.d); 
               $('.PreviewLink').trigger('click');  
            }
         };
         $.ajax(options);
    });    
}

jQuery(document).ready(function() 
{

    if (jQuery.isFunction(jQuery.fn.nivoSlider)) 
    {
        $('#slider').nivoSlider({
            effect: 'fade',
            animSpeed: 400,
            directionNav: false,
            afterChange: function() { },
            pauseTime: 6000
        });
    }


    $(document).pngFix();
    carousel = jQuery('#mycarousel').jcarousel({ initCallback: carousel_callback });



    renderToolTip();
    bindImageDisplay();
    bindWebAddress();
    bindBackToOriginalText();
    bindParticipantSearch();
    bindRegistration();
    bindCampaignManager();

    $('#mycarousel').css('visibility', 'visible');




});

 function addCarrouselImage( imagesrc )
 {    
     iscover = false;

     var total = $(".pictureCount").html();
    
     if(removeBaseImage)
     {
        removeImageUrlArray(baseImagePath);
        removeUrl(baseImagePath);
       
        $("div[thumbid='" + baseImagePath + "']").parent().remove();
       
        currentcarousel.size( currentcarousel.size() - 1)
        removeBaseImage= false;
        iscover = true;
       
        total--;
        $(".pictureCount").html(total); 
        
        //if we remove the base image, we put back the behaviour
        $('.jqDeleteImageJULY2010').css('visibility','visible'); 
        $('.jqDeleteImageJULY2010').css('display','block'); 
     }     
     
     
     // if we add baseimage, we remove Delete behaviour
     if( imagesrc == baseImagePath )
     {
        $('.jqDeleteImageJULY2010').css('visibility','hidden'); 
        $('.jqDeleteImageJULY2010').css('display','none'); 
     }
     
     // there only one image left so i must be the image cover   
     if( total == 0) { iscover = true;}
     
     currentThumbID = imagesrc ;

     $('.profileImage').attr('src', imagesrc );
     var newsize = currentcarousel.size() + 1;
     
//     alert(newsize );
     currentcarousel.add(newsize , mycarousel_getItemHTML(imagesrc,iscover));
     currentcarousel.size(newsize )
    
      addImageUrl(imagesrc, iscover);
    
     currentcarousel.scroll(currentcarousel.last, false);
    
    
     $("div[thumbid='" + currentThumbID + "']").mouseover( MouseOverPicture );
     $("div[thumbid='" + currentThumbID + "']").trigger('click');
     
     var total = $(".pictureCount").html();
     total++;
     $(".pictureCount").html(total);   
     
     CurrentMaxImage--;
     
      $('#fileInput').uploadifySettings('queueSizeLimit',CurrentMaxImage); 
       
     $.ajax({
     url: '/Components/User/PictureGallery/ajax.aspx',
     dataType : 'text',
     data: "addUrl=" + imagesrc ,
     success: function(data) {}});    
     
}

function changeCurrentImage(imagesrc)
{
    $('.profileImage').attr('src', imagesrc );    
     $.ajax({
     url: '/Components/User/PictureGallery/ajax.aspx',
     dataType : 'text',
     data: "flush=1&addUrl=" + imagesrc ,
     success: function(data) {}});
}
