var xdonation = 0; // value of the ammount field inputed
var xsupport = 0;  // calculation of support from xdonation
var csupport = true; // support checkbox selected
var xtotal = 0; // value of total donation, xdonation + xsupport
var inprogress = false; // bolean for inisde donation under progress
var outsideformloaded = false; // bolean for outside donation form is loaded with ajaxed id
var donationlimit = 5; // minimun to donate
var userlogin = 0;  // 0 not, 1 yes
var insideDonationEmilerTrigger = 0; // email trigger

$(document).ready(function() {
   
  // $("#sharelink").live('click', function() {
//		$(this).select();
//	});

   //select text in widget lightbox, animate lenght of input field
   $("#sharelink").focus(function () {
      $("#sharelink").animate({width: '350px'},100,'easeOutQuad',function() {
                     $(this).select();
                     });
   });

   $("#sharelink").focusout(function () {
         $(this).animate({
    width: '140px'});
    });
   
    $("#mgverified").tooltip({
        // place tooltip on the right edge
        position: 'bottom center',
        // a little tweaking of the position
        offset: [7, 0],
        // use the built-in fadeIn/fadeOut effect
        effect: 'fade',
        // custom opacity setting
        opacity: 0.9
 
   });

   
   //select text in widget lightbox
    $(".cbwboptions textarea").focus(function () {
 
                     $(this).select();
                   
   });
   
   
  
   // $.fn.colorbox.init();


  /* override some default options
 $("#crowd_right_column").find(".crowd_reward").expander({
    slicePoint:       140,  // default is 100
    expandText:         'read more', // default is 'read more...'
    collapseTimer:    0, // re-collapses after 5 seconds; default is 0, so no re-collapsing
    expandEffect:     'fadeIn',
    userCollapseText: '[ ^ ]'  // default is '[collapse expanded text]'
  });
  */

   $("a[rel='cbSendMessage']").colorbox({width:"700", inline:true, scrolling:false,  href:"#cbMessagebox",
                                        onCleanup:function(){
                                          
                                          },
                                        onClosed:function(){
                                          //$("#processingoff").show();
                                          //$("#processingsuccess").hide();
                                          $("#msgsubject").removeAttr('disabled');
                                          $("#msgtext").removeAttr('disabled');
                                          $('#msgsubject').val('');
                                          $('#msgtext').val('');
                                       }});
      //Color box for Widget
      $("a[rel='cbWidget']").colorbox({width:"750", inline:true, scrolling:false,  href:"#cbWidgetbox"});

      // launch colorbox lightbox when donatebotton click
      $("a[rel='cbDonateOutisde']").colorbox({width:"700", inline:true, scrolling:false,  href:"#DFbox"});
      $("a[rel='cbDonateInside']").colorbox({width:"700",
                                            overlayClose:false,
                                            escKey:false,
                                            inline:true,
                                            scrolling:false,
                                            href:"#DFboxIn",
                                            onClosed:function(){
                                                if(inprogress==true){
                                                   location.reload();
                                                }}
                                            });
      
      //when logged in donor click on donate
      $("input[rel='donateinside']").click(function(){
         $("#todonateinside").attr('disabled', 'disabled');
         inprogress = true;
         $("#cboxClose").hide();
         $("#processingoff").hide();
         $("#processingon").show();
         $("#donationerror").text("");
         
         var check = $("#anonymous").is(':checked');
         if (check == true){
               anonymous = 1;
         }else {
               anonymous = 0;
         }
         
         $.ajax({
            type: "POST",
            url: DONORS_URL + "profile/_insideDonation/",
            data: ({"amount" : xtotal,
                   "donhash": $("#donhash").val(),
                   "request_id": $("#request_id").val(),
                   "request_user_id": $("#request_user_id").val(),
                   "anonymous": anonymous}),
            
            success: function(msg){
                //alert(msg); for debugging
               var str = msg.split('#');
               var returnid = str[0];
               var transactionid = str[1];
               var amountdonated = str[2];
               var email = str[3];
               
               var result = parseInt(returnid);
               switch (result)
               {
                  case 1:
                     
                     window.setTimeout(function() {
                        $(".DFrightside").slideUp('400', function() {
                           $("#returnamount").text("$ "+amountdonated);
                           $("#returntransid").text(transactionid);
                           sendEmailofInsideDonation(transactionid, amountdonated, email);
                           window.setTimeout(function() {
                              $(".DFrightsidethankyou").slideDown('400');
                              
                           },500);
                        });
                     }, 1000);
                     break;
                     
                  case 2:
                     deployErrorMessageForInsideDonation('Sorry, there is not enough funds in your account.');
                     break;
                  
                  
                  case 3:
                     deployErrorMessageForInsideDonation('Minimum donation of $1 please');
                     break;
                  
                  case 4:
                     deployErrorMessageForInsideDonation('Hash not valid');
                     break;
                  
                   default:
                     deployErrorMessageForInsideDonation('Sorry, An error has occurr please try again');
                   break;
               }
            }
         });
         
         return false;
      });

    $("#mgsupportvalue").text("$ "+xsupport);
    $("#mgtotaldonation").text("$ "+xtotal);
    disableSubmitButton();

// Outside behavior
// When user (not logged in) donates to recipient
   $("#donationform").submit(function() {
      if(outsideformloaded == false){
         $("#processingoff").hide();
         $("#processingon").show();
         var loginID = $('#x_login').val();
        var sequense = $('#x_fp_sequence').val();
	var time = $('#x_fp_timestamp').val();
	var amount = xtotal;
         $.post(MAIN_URL + 'profile/fingerprint/',{ 'loginID': loginID, 'sequence': sequense, 'timeStamp' : time, 'amount' : amount  } , function(success) {

            outsideformloaded = true;
            $('#x_fp_hash').val(success);
            $('#x_amount').val(xtotal);
            window.setTimeout(function() {
                $("#donationform").submit();
            },1000);
            
	});
         return false;
      }
      
      return true;
    });


    $("input[name=todonate]").change(function(){
	userlogin = 0;
        xdonation = parseFloat($(this).val());
	calculatesupport();
	calculatetotal();
	buttonSubmition();
	});
    
    $("input[name=todonate]").keyup(function(){
        userlogin = 0;
	res(this,numb);
	xdonation = parseFloat($(this).val());
	calculatesupport();
	calculatetotal();
	buttonSubmition();
	});
    //--!>
    
// Inside behavior
// When logged in donors donates to recipeint
    $("input[name=todonateinside]").change(function(){
	userlogin = 1;
        xdonation = parseFloat($(this).val());
	//calculatesupport();
	calculatetotalinside();
	buttonSubmition();
        $("#donationerror").text("");
      	});
    
    $("input[name=todonateinside]").keyup(function(){
         userlogin = 1;
	res(this,numb);
	xdonation = parseFloat($(this).val());
	//calculatesupport();
	calculatetotalinside();
	$("#donationerror").text("");
	buttonSubmition();
        
	});    
   //--!>
   
   
    $("input[id=mgsupport]").click(function(){
    	var check = $(this).is(':checked');
	
	if (check == true){
	    csupport = true;
	    calculatesupport();
	    calculatetotal();
	}else {
	    csupport = false;
	    xsupport = 0;
	    calculatesupport();
	    calculatetotal();
	}

    });
    
    //wizard form tooltips parameters
    $('#wizardform :input[type="text"]').tooltip({

	// place tooltip on the right edge
	position: "center right",

	// a little tweaking of the position
	offset: [-2, 10],

	// use the built-in fadeIn/fadeOut effect
	effect: "fade",

	// custom opacity setting
	opacity: 0.7

   });
    
// Send Private Message
   $("#profilemessageform").submit(function() {
      var subject = $('#msgsubject').val();
      var message = $('#msgtext').val();
      var userid = $('#userid').val();
   
      if( message=='' || message == null || subject=='' || subject==null || userid==''){
         alert('Please write a subject and a message!');
      }else{
         
         $("#msgsubject").attr('disabled', 'disabled');
         $("#msgtext").attr('disabled', 'disabled');
         
         $("#processingoff").hide();
         $("#processingon").show();
         
   
         $.get(MAIN_URL + 'profile/sendmessage/',{ 'subject': subject, 'message': message, 'userid' : userid} ,
                function(success) {

            outsideformloaded = true;
            
            $("#processingon").hide();
            $("#processingsuccess").show();
            
            setTimeout(function(){
              $("#processingsuccess").hide();
              $("#processingoff").show();
              $.fn.colorbox.close();
            },2000);
            
	});
         
      }
         return false;
     
    });
    
    // if user in wizard, set image uploader parameters
    if(ACTION == 'wizard'){
      $("#avatar").uploadify({
		'uploader'       : ASSETS_URL+'flash/uploadify.swf',
		'script'         : CURRENT_URL+'uploadify.php',
                'scriptData'     : {'name': UNAME, 'id':UDID},
                'scriptAccess'   : 'always',
		'cancelImg'      : ASSETS_IMAGES_URL+'uploadify_cancel.png',
		'folder'         : 'STATIC_URL/images',
		'wmode'          : 'transparent',
		'width'          : 130,
		'auto'           : true,
		'multi'          : false,
		onComplete: function (evt, queueID, fileObj, response, data) {
			showpic(response);
		}
   });
    }
   

});

function calculatesupport(){
    if(csupport && validateammount() == true){
	var xsupport2 = xdonation * .15;
	xsupport = Math.round(xsupport2*100)/100;
	
	$("#mgsupportvalue").text("$ "+xsupport);
    } else {
	
	xsupport = 0;
	xsupportV = 0;
	$("#mgsupportvalue").text("$ "+xsupport);
    }
};

function calculatetotal(){
    if(validateammount() == true){
	var xtotal2 = xdonation + xsupport;
	xtotal = Math.round(xtotal2*100)/100;
	$("#mgtotaldonation").text("$ "+xtotal);
	//getfingerprint();
    } else {
	xtotal = 0;
	$("#mgtotaldonation").text("$ "+xtotal);
    }
};

function calculatetotalinside(){
    if(validateammount() == true){
	var xtotal2 = xdonation + xsupport;
	xtotal = Math.round(xtotal2*100)/100;
	$("#mgtotaldonation").text("$ "+xtotal);
    } else {
	xtotal = 0;
	$("#mgtotaldonation").text("$ "+xtotal);
    }
};

function disableSubmitButton(){
        $("input[id='submitbutton']").attr('disabled', 'disabled').removeClass('dfbtnenable').addClass('dfbtndisable');
};

function enableSubmitButton(){
        $("input[id='submitbutton']").removeAttr('disabled').removeClass('dfbtndisable').addClass('dfbtnenable');
};

function validateammount(){
    isitNaN = isNaN(xdonation);
    if (xdonation == 0 || xdonation == "" || xdonation == "NaN" || xdonation == null || isitNaN == true || userlogin == 0 && xdonation < donationlimit){
         if (userlogin == 0 && xdonation < donationlimit){
         setTimeout(function(){
            showErrorMessage('$5 Minimum Please');
            },10);
                    
         }
	return false;
    }else {
	return true;
    }
    
};

function showErrorMessage(text){
   $('#mgtotaldonation').text(text);
}

function getfingerprint() {
    	var loginID = $('#x_login').val();
        var sequense = $('#x_fp_sequence').val();
	var time = $('#x_fp_timestamp').val();
	var amount = xtotal;

	
	$.post(MAIN_URL + 'profile/fingerprint/',{ 'loginID': loginID, 'sequence': sequense, 'timeStamp' : time, 'amount' : amount  } , function(success) {

	$('#x_fp_hash').val(success);
	$('#x_amount').val(xtotal);
	});

};

function showpic(img){
            
            $('#picload').html('<img src="'+img+'_thumb" border="0" />');
            $('#picload').fadeIn('slow');
}

function buttonSubmition(){
    
    if(validateammount() == true ){
	enableSubmitButton();
    } else {
	disableSubmitButton();
    }
};

function sendEmailofInsideDonation(transactionid, amountdonated, email){
   
  
   
    if(insideDonationEmilerTrigger == 0){
        insideDonationEmilerTrigger = 1;
        $.ajax({
            type: "POST",
            url: DONORS_URL+"php_emailer_inside_donation.php",
            data: ({"donor_name": $("#donor_user_nick").text(),
                     "nickname" : $("#nickname").val(),
                     "recipient_id": $("#request_user_id").val(),
                     "transactionid": transactionid,
                     "purl": $("#purl").val(),
                     "amount" : amountdonated,
                     "donor_email": email})

              
        });
    }
}


function deployErrorMessageForInsideDonation(error){
   $("#todonateinside").val('');
   $("#todonateinside").removeAttr("disabled");
   inprogress = false;
   $("#cboxClose").show();
   $("#processingon").hide();
   $("#processingoff").show();
   disableSubmitButton();
   $("#mgtotaldonation").text("$ 0");
   $("#donationerror").text(error);
   
}
