//
//  @copyright Copyright (c) 2011 Triton Digital Media LLC
// 
//   Change Log:
// 
//        USERNAME        DATE      COMMENT
//   ----------------- ---------- -----------------------------------------------------------------------------------
// 
//
//
// Setup initial jQuery items - dialogs, tablesorter, buttons, tabs, etc.
//
jQuery(document).ready( function() {
  (function($) {
    consoleX({ debug: true, mode: 'log', message: 'document.ready(): Enter.' });
    var urlParams = {};

    // Unknown jQuery Datepicker.
    if ( $( '#datepicker' )[0] ) {
      consoleX({ debug: true, mode: 'log', message: 'document.ready(): init jQuery datepicker "#datepicker".' });
      $( "#datepicker" ).datepicker({dateFormat: 'yy-mm-dd'});
    }

    // Social Post jQuery Datepicker.
    if ( $('#ts_socialpost_datepicker' )[0] ) {
      consoleX({ debug: true, mode: 'log', message: 'document.ready(): init jQuery datepicker "#ts_socialpost_datepicker".' });
      $( "#ts_socialpost_datepicker" ).datepicker({dateFormat: 'yy-mm-dd', minDate: new Date()});
    }
    
    $("button.ts_button").click(function(event) {
  	  event.preventDefault();
    });    
    
  })(jQuery);
});


/* For development debugging only.
 *
 */
function tsDestroyPostPopUp() {
  consoleX({ debug: true, mode: 'log', message: 'tsDestroyPostPopUp(): Enter' });
  jQuery( '#ts_socialpost_master_container' ).html( '' );
  jQuery( '#ts_socialpost_master_container' ).dialog( 'destroy' );
}


/*
 *
 */
function tsSocialcreatePostPopUp( ) {
  consoleX({ debug: true, mode: 'log', message: 'tsSocialcreatePostPopUp(): Enter.' });
  try {
    // Make sure the target container already exists, if not create it.
    if ( jQuery( '#ts_socialpost_master_container' ).length ) {
      consoleX({ debug: true, mode: 'log', message: 'tsSocialcreatePostPopUp(): "#ts_socialpost_master_container" exists.' });
    } else {
      consoleX({ debug: true, mode: 'log', message: 'tsSocialcreatePostPopUp(): "#ts_socialpost_master_container" does not exist, creating.' });
      jQuery( 'body' ).append( "<div class='ts_socialpost_master_container' id='ts_socialpost_master_container' title='Post to Social Media'><\/div>" );
      tsSocialInitPostPopUp();
    }

    consoleX({ debug: true, mode: 'log', message: 'tsSocialcreatePostPopUp(): ajax call "/admin/modules/social/popup_div/social_post.php?accounts=..."' });
    consoleX({ debug: true, mode: 'dir', message: affiliate_account_list });

    jQuery.ajax({
      type: 'POST',
      url:  '/admin/modules/social/popup_div/social_post.php',
      data: 'accounts='+ JSON.stringify( affiliate_account_list ),
      update: true,
      success: function( data ) {
        consoleX({ debug: true, mode: 'log', message: 'tsSocialcreatePostPopUp(): ajax success.' });
        //consoleX({ debug: true, mode: 'log', message: data });

        // Fill the container with our updated post widget.
        jQuery( '#ts_socialpost_master_container' ).html( data );

      },
      error: function( jqXHR, textStatus, errorThrown ) {
        consoleX({ debug: true, mode: 'error', message: 'tsSocialcreatePostPopUp(): textStatus = "'+ textStatus +'", errorThrown = "'+ errorThrown +'"' });
      }
    });
  } catch(e) {
    consoleX({ debug: true, mode: 'error', message: 'tsSocialcreatePostPopUp(): Exception = "'+ e +'"' });
  }
}


/*
 *
 */
function tsSocialInitPostPopUp() {
  consoleX({ debug: true, mode: 'log', message: 'tsSocialInitPostPopUp(): Enter.' });
  try {
    // Social Post Popup.
    if ( jQuery( '#ts_socialpost_master_container' )[0]) {
      consoleX({ debug: true, mode: 'log', message: 'tsSocialInitPostPopUp(): init "#ts_socialpost_master_container" dialog.' });
      jQuery( '#ts_socialpost_master_container' ).dialog({
         modal:         true,
         closeOnEscape: false,
         width:         555,
         minWidth:      555,
         maxWidth:      'auto',
         height:        'auto',
         minHeight:     200,
         maxHeight:     'auto',
         autoOpen:      false
      });
    }

    // Create the event.  IE any items set to this class will open the dialog on click.
    if ( jQuery( '.ts_socialpost_button' )[0] ) {
      consoleX({ debug: true, mode: 'log', message: 'tsSocialInitPostPopUp(): init ".ts_socialpost_button" button.' });
      jQuery( '.ts_socialpost_button' ).click( function(target) {
        tsSocialPostForModule( target );
      });
    }

    // Clean up on close of social post dialog.
    jQuery( '#ts_socialpost_master_container' ).dialog({
      close: function() {
        tsSocialPostPopulateDialog();
      }
    });

  } catch(e) {
    consoleX({ debug: true, mode: 'error', message: 'tsSocialInitPostPopUp(): Exception = "'+ e +'"' });
  }
}


/*
 * Handles a click event on a Social Post icon from an admin module.
 */
function tsSocialPostForModule( event ) {
  consoleX({ debug: true, mode: 'log', message: 'tsSocialPostForModule(): Enter' });
  if ( event && event.currentTarget.getAttribute('rel') ) {
    event.stopPropagation();
    event.stopImmediatePropagation();
    event.preventDefault();
    consoleX({ debug: true, mode: 'log', message: 'tsSocialPostForModule(): ajax call "/admin/modules/social/actions/get_module_social_params.php?ref='+ event.currentTarget.getAttribute('rel') });
    jQuery.ajax({
      url:      '/admin/modules/social/actions/get_module_social_params.php',
      global:   false,
      type:     'GET',
      data:     ({ref:event.currentTarget.getAttribute('rel')}),
      dataType: 'json',
      async:    false,
      success:  function( result ) {
        consoleX({ debug: true, mode: 'log', message: 'tsSocialPostForModule(): ajax success' });
        consoleX({ debug: true, mode: 'log', message: result });
        if ( result.stat != 'error') {
          jQuery( '#ts_socialpost_master_container' ).dialog( 'open' );
          tsSocialPostPopulateDialog(
            null,
            'add',
            result.msg,
            result.link,
            result.image,
            result.title,
            result.tagline,
            result.desc,
            result.footer_text,
            result.footer_link
          );
        } else {
          alert("There was an error preparing your post. Please contact your administrator.");
          consoleX({ debug: true, mode: 'error', message: 'tsSocialPostForModule(): Error preparing for post. (code: '+ result.error.code + ', msg: '+ result.error.message + ').' });
        }
      },
      error: function( jqXHR, textStatus, errorThrown ) {
        consoleX({ debug: true, mode: 'error', message: 'tsSocialPostForModule(): textStatus = "'+ textStatus +'", errorThrown = "'+ errorThrown +'".' });
      }
    });
  }
  return false;
}


/*
 * Handles an AJAX loading of the share / like widget anchors on the front-end
 */
function tsSocialPrintShareLike( div_id, affiliate_id, affiliate_auth, curr_module_id, curr_ref_id, affiliate_url, providers, xml_file, params ) {
  consoleX({ debug: true, mode: 'log', message: 'tsSocialPrintShareLike(): Enter.' });
  var div_obj = document.getElementById( div_id );

  if ( div_obj ) {
    var share_like_enabled =  ({'allow_share':false, 'allow_like':false});
    consoleX({ debug: true, mode: 'log', message: 'tsSocialPrintShareLike(): ajax call "/admin/modules/social/actions/get_module_share_like_enabled.php?module_id='+ curr_module_id +'"' });
    jQuery.ajax({
      url:      '/admin/modules/social/actions/get_module_share_like_enabled.php',
      global:   false,
      type:     "GET",
      data:     ({module_id:curr_module_id, reference_id:curr_ref_id}),
      dataType: "json",
      async:    false,
      success:  function( result ) {
        consoleX({ debug: true, mode: 'log', message: 'tsSocialPrintShareLike(): ajax success.' });
        consoleX({ debug: true, mode: 'log', message: result });
        if ( result.stat != 'error' ) {
          share_like_enabled = result;
        } else {
          consoleX({ debug: true, mode: 'error', message: 'tsSocialPrintShareLike():Error preparing for Share. (code: '+ result.error.code +', msg: '+ result.error.message +')' });
        }
      },
      error: function( jqXHR, textStatus, errorThrown ) {
        consoleX({ debug: true, mode: 'error', message: 'tsSocialPrintShareLike(): textStatus = "'+ textStatus +'", errorThrown = "'+ errorThrown +'"' });
      }
    });

    // remove the old share / like iframes and code.
    jQuery(div_obj).html('');

    //
    // Get the parameters for the share and like, and then build the anchors.
    //
    consoleX({ debug: true, mode: 'log', message: 'tsSocialPrintShareLike(): ajax call "/admin/modules/social/actions/get_module_social_params.php' });
    jQuery.ajax({
      url:      '/admin/modules/social/actions/get_module_social_params.php',
      global:   false,
      type:     "GET",
      data:     ({ref:xml_file+":"+ params}),
      dataType: "json",
      async:    false,
      success:  function( result ) {
        consoleX({ debug: true, mode: 'log', message: 'tsSocialPrintShareLike(): ajax success' });
        consoleX({ debug: true, mode: 'log', message: result });
        if ( result.stat != 'error') {
          var shareLikeString = "";

          if( share_like_enabled.allow_like == 'y' ) {
          shareLikeString += "<div style='display:inline-block;vertical-align: middle;'><a href='#' rel='tssolike' tssodata='{\"link\":\"" +
                             escape( result.link ? result.link : '' ) +
                             "\",\"title\":\"" +
                             escape( result.title ? result.title : '' )  +
                             "\",\"type\":\"affiliate\"}'><\/a><\/div>";
          }

          if ( share_like_enabled.allow_share == 'y' ) {
            var share_data = ({ 'message' : ( result.msg ? escape(result.msg) : '' ),
                                'link' :( result.link ? result.link : '' ),
                                'image' :( result.image ? result.image : '' ),
                                'title' :( result.title ? escape(result.title) : '' ),
                                'tagline' :( result.tagline ? escape(result.tagline) : '' ),
                                'description' :( result.desc ? escape(result.desc) : '' ),
                                'footer_text' :( result.footer_text ? escape(result.footer_text) : '' ),
                                'footer_link' : ( result.footer_link ? result.footer_link : '' )
                             });

            shareLikeString += "<div style='display:inline-block;vertical-align: middle;'><a href='#' rel='tssoshare' tssodata='" + array2json( share_data ) + "'>Share<\/a><\/div>";
          }

          // Set the new share / like for the div.
          jQuery( div_obj ).html( shareLikeString );

          jQuery( "a[rel^='tssoshare']" ).tssoshare({
            aid :       affiliate_id,
            auth:       affiliate_auth,
            url_return: affiliate_url,
            providers : providers
          });

          jQuery( "a[rel^='tssolike']" ).tssolike({
            aid:        affiliate_id,
            auth:       affiliate_auth,
            layout:     'button_count',
            show_faces: false,
            height:     25,
            url_return: affiliate_url
          });

          jQuery( "a[rel^='prettyPhoto']" ).prettyPhoto();

        } else {
          consoleX({ debug: true, mode: 'error', message: 'tsSocialPrintShareLike():Error preparing for Share. (code: '+ result.error.code +', msg: '+ result.error.message +')' });
        }
      },
      error: function( jqXHR, textStatus, errorThrown ) {
        consoleX({ debug: true, mode: 'error', message: 'tsSocialPrintShareLike(): textStatus = "'+ textStatus +'", errorThrown = "'+ errorThrown +'"' });
      }
    });
  }
  return false;
}

function tsSocialPrintFacebookComment( div_id, curr_module_id, affiliate_url, xml_file, params ) {
	
}



/**
 * Converts the given data structure to a JSON string.
 * Argument: arr - The data structure that must be converted to JSON
 * Example: var json_string = array2json(['e', {pluribus: 'unum'}]);
 *      var json = array2json({"success":"Sweet","failure":false,"empty_array":[],"numbers":[1,2,3],"info":{"name":"Binny","site":"http:\/\/www.openjs.com\/"}});
 * http://www.openjs.com/scripts/data/json_encode.php
 */
function array2json( arr ) {
  consoleX({ debug: true, mode: 'log', message: 'array2json(): Enter' });
  var parts = [];
  var is_list = ( Object.prototype.toString.apply(arr) === '[object Array]' );

  for ( var key in arr ) {
    var value = arr[key];
    if ( typeof value == "object" ) { //Custom handling for arrays
      if ( is_list ) {
        parts.push( array2json( value ) ); /* :RECURSION: */
      } else {
        parts[key] = array2json( value ); /* :RECURSION: */
      }
    } else {
      var str = '';

      if ( !is_list ) {
        str = '"' + key + '":';
      }

      //Custom handling for multiple data types
      if ( typeof value == "number" ) {
        str += value; //Numbers
      } else if ( false === value ) {
        str += 'false'; //The booleans
      } else if ( true === value ) {
        str += 'true';
      } else {
        str += '"' + value + '"'; //All other things
      }

      // :TODO: Is there any more datatype we should be in the lookout for? (Functions?)

      parts.push( str );
    }
  }
  var json = parts.join( "," );

  if ( is_list ) {
    return '['+ json +']';//Return numerical JSON
  }

  return '{'+ json +'}';//Return associative JSON
}


/*
 * Helper Method: consoleX
 *  Outputs to the browsers Console for debugging.
 *
 * Arguments:
 *   debug   : optional - but nothing will happen if this is not set to 'true'.
 *   mode    : optional - console output, either 'dir', 'error', 'warn', 'info', 'log' (default), 'group', 'groupEnd', 'time', 'timeEnd'.
 *   message : required for all but 'groupEnd'
 */
function consoleX() {
  //
  // Initialize and get all arguments.
  //
  var args = arguments[0] || {};
  if ( args.debug )   { var debug   = args.debug; }
  if ( args.mode )    { var mode    = args.mode; }
  if ( args.message ) { var message = args.message; }

  debug = false;
  
  //
  // Is Debug on (true) and is Console available (not undefined)?
  //
  if ( true == debug && typeof console != 'undefined' ) {
    if ( mode == 'error' && console.error ) {
      console.error( args.message );
    } else if ( mode == 'info' && console.info ) {
      console.info( args.message );
    } else if ( mode == 'warn' && console.warn ) {
      console.warn( args.message );
    } else if ( mode == 'dir' && console.dir ) {
      console.dir( args.message );
    } else if ( mode == 'group' && console.group ) {
      console.group( args.message );
    } else if ( mode == 'groupEnd' && console.groupEnd ) {
      console.groupEnd( );
    } else if ( mode == 'time' && console.time ) {
      console.time( args.message );
    } else if ( mode == 'timeEnd' && console.timeEnd ) {
      console.timeEnd( args.message );
    // Catch all.  All browsers understand 'log'.
    } else if ( console.log ) {
      console.log( args.message );
    }
  }
} // End: consoleX()

