/*
 * Traackr JavaScript Library
 * rramaiah: note - this file is still used for (only?) influencer-notes functionality
 *
 * Copyright - 2008-2010 Traackr, Inc. All rights reserved.
 */
if ( typeof( TRAACKR ) == "undefined" ) TRAACKR = {};

// Define trim() function for String
if(typeof String.prototype.trim !== 'function') {
   String.prototype.trim = function() {
      return $.trim(this);//this.replace(/^\s+|\s+$/, '');
   }
}

// Define console.log() if doesn't exist (IE)
if (!window.console) {
   window.console = {};
   window.console.log = function (text) { }
}

/*
 * Configure base URL for all ajax calls
 */
if ( typeof( TRAACKR_CF ) == "undefined" ) TRAACKR_CF = {};
TRAACKR_CF = {
   app_base_url: '/'
}


TRAACKR_func = function() {

   console.log('TRAACKR - Initializing');

   // Initialization works
   $(document).ready(function() {
      // If we use HTTP, get images to use their original URL
//      if ( location.protocol.substring(0, 5) == "http:" ) {
//         url_regex = /\/influencers\/avatar/;
//         img_regex = /img=(.+)$/;
//         $('img').each(
//            function() {
//               url = $(this).attr('src');
//               if ( url_regex.test(url) ) {
//                  img_url = url.match(img_regex);
//                  $(this).attr('src', $.URLDecode(img_url[1]));
//               }
//            }
//         );
//      }

      });

      $('.loading_spinner').text('Loading');

   /*             */
   /* Adds a note */
   /*             */
   var __add_note = function() {
      // prevent empty notes
      if( $('#add_note_form textarea').val().match(/^\s*$/) ) return false;
      $('#add_note_form').ajaxSubmit(__add_note_submit);
   } // End function __add_note()

   /*                                        */
   /* Callback function for form ajax submit */
   /*                                        */
   var __add_note_submit = function(data) {
      $('#notes').prepend(data);
      if ( document.add_note_form['data[InfluencerNote][text]'] ) {
         document.add_note_form['data[InfluencerNote][text]'].value = '';
      }
      if ( document.add_note_form['data[CampaignNote][text]'] ) {
         document.add_note_form['data[CampaignNote][text]'].value = '';
      }
      if ( document.add_note_form['data[PerformanceNote][description]'] ) {
         document.add_note_form['data[PerformanceNote][description]'].value = '';
      }
   } // End function __add_note_submit()

   /*                      */
   /* Makes notes editable */
   /*                      */
   var __set_editable_notes = function(type) {

      $('.editable_note').livequery(function(){
         $(this).editable(
            TRAACKR_CF.app_base_url+'influencer_notes/update',
            {data: function(value, settings) {
                  // Converts value which might include HTML entities back to text
                  // Have to convert <br> to nee line for IE
                  var v = value.replace(/<BR>/g, "\n");
                  //return $('<pre>').html(v).text().trim(); // Does not work on IE
                  return $('<pre>'+v+'</pre>').text().trim();
               },
               loaddata: {type: type},
               submitdata: {type: type},
	       type: 'textarea', onblur: 'submit',
          //use same styles as add-note textarea
          cssclass: 'add_note_textarea',
          rows:4,
          tooltip: 'Click to edit...'
            }
         );
      });
   } // End function __set_editable_notes

   /*                                                       */
   /* Deletes a note                                        */
   /* Can handle regular (influencer) and performance notes */
   /*                                                       */
   var __del_note = function(type, id) {
      $.get(
         TRAACKR_CF.app_base_url+'influencer_notes/delete/'+type+'/'+id,
         function(data){$('#note_'+id).hide('blind');}
      );
   } // End function __del_note()


/*

 Dialog box

*/

   var __campaign_dialog = function(domId, title, height, width, domIdArray) {
      $('#'+domId).dialog({
         open: function () {
            $(this).parents(".ui-dialog:first").find(".ui-dialog-titlebar").removeClass("ui-widget-header");
         },
         close: function () {
            for(i=0;i<domIdArray.length;i++) {
               $('#'+domIdArray[i]).val("");
               $('#'+domIdArray[i]).html("");
            }
         },
         draggable: false,
         position: ['center',100],
         autoOpen: false,
         resizable: false,
         title: title,
         height:height,
         width:width,
         modal: true,
         zIndex: 3999
      });
      return true;
   }

   console.log('TRAACKR - Initialization done.');

   /*                   */
   /*  Public functions */
   /*                   */
   return {
      // Notes functions
      notes: {
         del: __del_note,
         add: __add_note,
         set_editable: __set_editable_notes
      },
      // Campaigns functions
      campaigns: {
         campaign_dialog:__campaign_dialog

      }

   } // End return public functions

}; // End library TRAACKR


/*
 * Add trim() function to String
 */
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
} // End function trim()

/*
 * Filter searches displayed
 */
var filter_searches = function(search_class) {

      $('div.search').hide();
      $('div.'+search_class).show();

} // End function filter_searches()


var getDateObject= function(dateString,dateSeperator)
{
	//This function return a date object after accepting
	//a date string ans dateseparator as arguments
	var curValue=dateString;
	var sepChar=dateSeperator;
	var curPos=0;
	var cDate,cMonth,cYear;

	//extract day portion
	curPos=dateString.indexOf(sepChar);
	cDate=dateString.substring(0,curPos);

	//extract month portion
	endPos=dateString.indexOf(sepChar,curPos+1);
        cMonth=dateString.substring(curPos+1,endPos);

	//extract year portion
	curPos=endPos;
	endPos=curPos+5;
	cYear=curValue.substring(curPos+1,endPos);

	//Create Date Object
	dtObject=new Date(cYear,cMonth,cDate);
	return dtObject;
}



/* Create new campaign */
var form_submit = function ()
{
   var name = $("#id_campaignName").val();
   if($("#id_authority_count").val()=="Other")
      var aut_count = $("#id_authority_count_other").val();
   else
      var aut_count = $("#id_authority_count").val();

   if(!name.match(/^\s*$/) && !aut_count.match(/^\s*$/) && !isNaN(aut_count) && parseInt(aut_count)>0)
   {
      $('#createCampaignfrm').submit();
   }
   else
   {
      if(!name.match(/^\s*$/) || isNaN(aut_count))
	 $("#msg").html("Please select number of influencers.");
      return false;
   }
}

var select_authority_count = function(select_id) {
		if($("#"+select_id).find('option:selected').val() === 'Other') {
			$('span.authority_count_other').show();
			return;
		}
		$('span.authority_count_other').hide();
};

/* need to move to top of file...
var avatar_img_placeholder = function(img) {
      if ( img.height <= 48 ) {
         img.src = TRAACKR_CF.app_base_url+'img/blank_avatar.png';
      }
      else {
         img.src = TRAACKR_CF.app_base_url+'img/blank_avatar_73.png';
      }
};
*/

