jQuery(document).ready(function() {
  applyJqueryTriggers(document);
});

function urlTriggers(startingPoint) {
  $(".urlField", startingPoint).click(function(e) {
    var urlToChange = this;
    var parentTag = $(this).parent();
    var newAId = this.id;
    e.preventDefault();
    var url = $(this).html();
    parentTag.append("<span id='SPAN"+newAId+"'><br />Go To Link: <a href='" + url + "'>"+url+"</a> - <a id='CHANGE"+newAId+"' href='#'>Change</a></span>");
    $("#CHANGE"+newAId).click(function(e){
      e.preventDefault();
      $("#SPAN"+newAId).each(function(e){
        $(this).html("<br /><input id='urlInput"+newAId+"' value='"+url+"' size='"+(url.length+10)+"' /><button id='urlSave"+newAId+"'>Save</button>");
      });
      $("#urlSave"+newAId).click(function(e){
        var newUrl = $("#urlInput"+newAId).val();

        //save the changes
        //Split out the nonsense from the needed data
        idArrayPhase1 = urlToChange.id.split("_-_");
        //debug(idArrayPhase1[0]);
        idArray = idArrayPhase1[0].split("_");

        //debug(idArray.length);
        var fieldsCount = idArray.length - 2;

        // build request
        myJsonQuery = { action: "xmlDBUpdate" };
        //myJsonQuery['function'] = paramCount;
        myJsonQuery['table'] = idArray[0];
        myJsonQuery['primarykeyid'] = idArray[1];
        myJsonQuery['fields'] = fieldsCount;
        myJsonQuery['id'] = urlToChange.id;
        myJsonQuery['field1'] = idArray[2];

        value = newUrl.replace("#", "%23");
        value = value.replace("&", "%26");
        myJsonQuery['value1'] = value;

        // send request
        $.post( getpathtoxml() + "webfiles/xml.php",  myJsonQuery, function(result) {
          // format and output result

          if (typeof XMLSerializer != "undefined") {
            var xmlString = (new XMLSerializer()).serializeToString(result);
          } else {
            var xmlString = result.xml;
          }

          var status = removeWrapper(xmlString, 'status');

          if (status == 'success') {
            $(urlToChange).html(newUrl);
            $("#SPAN"+newAId).remove();
          } else {
            alert("Error saving data.");
            //debug(status);
            $(urlToChange).html(url);
            $("#SPAN"+newAId).remove();
          }
        }); 
      });
    });
  });
}

function cropImageTriggers(startingPoint) {
  $(".cropImage", startingPoint).click(function(e) {
    var idArray = this.id.split("_");

    if (idArray.length = 3) {
      $("#img" + idArray[1]).each(function(e) {
        var oldSrc = this.getAttribute("src");
				ratioArray = idArray[2].split("x");

				if (ratioArray.length == 2) {
					var offset = document.getElementById("offset_" + idArray[1]).value;
					var newSrc = oldSrc + "&ratio1="+ratioArray[0]+"&ratio2="+ratioArray[1] +"&x=500&y=500";
					if (offset != -1) {
						newSrc = newSrc + "&offset="+offset;
					}
					debug(newSrc);
					var newImage = "<img src='" + newSrc + "' alt='croppedImage' />";
					$("#crop_" + idArray[1] + "_div").html(newImage);
				} else {
					alert("Invalid ratio specified.");
				}
      });
    }
  });
}


function requiredTriggers(startingPoint) {
  $(".dependsOnRequired", startingPoint).click(function(e) {
    var idArray = this.id.split("_");
    var allowUpload = true;

    if (idArray.length = 2) {
      $(".required" + idArray[1]).each(function(e) {
        if ($(this).val().length == 0) {
          allowUpload = false;
        }
      });
    }

    if(!allowUpload) {
      alert("Required Field Missing");
      e.preventDefault();
    } else {
    }
  });
}

function mediaVoteTriggers(startingPoint) {
  $(".voteUp", startingPoint).click(function(e) {
    var voteUp = this;

    idArray = this.id.split("_");
    var mediaId = idArray[1];
    var voteDown = document.getElementById('mediavd' + "_" + mediaId);

    // build request
    myJsonQuery = { action: "xmlMediaVote" };
    //myJsonQuery['function'] = paramCount;
    myJsonQuery['userMediaID'] = mediaId;
    myJsonQuery['voteDirection'] = 'up';
    $.post( getpathtoxml() + "webfiles/xml.php",  myJsonQuery, function(result) {
      if (typeof XMLSerializer != "undefined") {
        var xmlString = (new XMLSerializer()).serializeToString(result);
      } else {
        var xmlString = result.xml;
      }

      var status = removeWrapper(xmlString, 'status');
      var statusArray = status.split("_");
      if (statusArray[0] == 'ok') {
        $(voteUp).attr('class','voteUp selected');
        $(voteDown).attr('class','voteDown');
        $("#mediavtotal_" + mediaId).html(statusArray[1]);
        $("#mediavwarning_" + mediaId).html('');
      } else {
        $("#mediavwarning_" + mediaId).html("&nbsp;" + status);
      }
    });
  });
  $(".voteDown", startingPoint).click(function(e) {
    var voteDown = this;

    idArray = this.id.split("_");
    var mediaId = idArray[1];
    var voteUp = document.getElementById('mediavu' + "_" + mediaId);

    // build request
    myJsonQuery = { action: "xmlMediaVote" };
    //myJsonQuery['function'] = paramCount;
    myJsonQuery['userMediaID'] = idArray[1];
    myJsonQuery['voteDirection'] = 'down';
    $.post( getpathtoxml() + "webfiles/xml.php",  myJsonQuery, function(result) {
      if (typeof XMLSerializer != "undefined") {
        var xmlString = (new XMLSerializer()).serializeToString(result);
      } else {
        var xmlString = result.xml;
      }

      var status = removeWrapper(xmlString, 'status');
      var statusArray = status.split("_");
      if (statusArray[0] == 'ok') {
        $(voteDown).attr('class','voteDown selected');
        $(voteUp).attr('class','voteUp');
        $("#mediavtotal_" + mediaId).html(statusArray[1]);
        $("#mediavwarning_" + mediaId).html('');
      } else {
        $("#mediavwarning_" + mediaId).html("&nbsp;" + status);        
      }
    });
  });
}

function tableVoteTriggers(startingPoint) {
  $(".tableVoteUp", startingPoint).click(function(e) {
    var voteUp = this;

    idArray = this.id.split("_");
    var tableId = idArray[1];
    var fieldId = idArray[2];
    var primaryKey = idArray[3];
    var voteDown = document.getElementById('voteUpDownvd' + "_" + tableId + "_" + fieldId + "_" + primaryKey);

    // build request
    myJsonQuery = { action: "xmlTableVote" };
    //myJsonQuery['function'] = paramCount;
    myJsonQuery['tableId'] = tableId;
    myJsonQuery['fieldId'] = fieldId;
    myJsonQuery['primaryKey'] = primaryKey;
    myJsonQuery['voteDirection'] = 'up';
    $.post( getpathtoxml() + "webfiles/xml.php",  myJsonQuery, function(result) {
      if (typeof XMLSerializer != "undefined") {
        var xmlString = (new XMLSerializer()).serializeToString(result);
      } else {
        var xmlString = result.xml;
      }

      var status = removeWrapper(xmlString, 'status');
      var statusArray = status.split("_");
      if (statusArray[0] == 'ok') {
        $(voteUp).attr('class','tableVoteUp selected');
        $(voteDown).attr('class','tableVoteDown');
        $("#tableVoteTotal_" + tableId + '_' + fieldId + '_' + primaryKey).html(statusArray[1]);
        $("#tableVoteWarning_" + tableId + '_' + fieldId + '_' + primaryKey).html('');
      } else {
        $("#tableVoteWarning_" + tableId + '_' + fieldId + '_' + primaryKey).html(status);
      }
    });
  });
  $(".tableVoteDown", startingPoint).click(function(e) {
    var voteDown = this;

    idArray = this.id.split("_");
    var tableId = idArray[1];
    var fieldId = idArray[2];
    var primaryKey = idArray[3];
    var voteUp = document.getElementById('voteUpDownvu' + "_" + tableId + "_" + fieldId + "_" + primaryKey);

    // build request
    myJsonQuery = { action: "xmlTableVote" };
    //myJsonQuery['function'] = paramCount;
    myJsonQuery['tableId'] = tableId;
    myJsonQuery['fieldId'] = fieldId;
    myJsonQuery['primaryKey'] = primaryKey;
    myJsonQuery['voteDirection'] = 'down';
    $.post( getpathtoxml() + "webfiles/xml.php",  myJsonQuery, function(result) {
      if (typeof XMLSerializer != "undefined") {
        var xmlString = (new XMLSerializer()).serializeToString(result);
      } else {
        var xmlString = result.xml;
      }

      var status = removeWrapper(xmlString, 'status');
      var statusArray = status.split("_");
      if (statusArray[0] == 'ok') {
        $(voteDown).attr('class','voteDown selected');
        $(voteUp).attr('class','voteUp');
        $("#tableVoteTotal_" + tableId + '_' + fieldId + '_' + primaryKey).html(statusArray[1]);
        $("#tableVoteWarning_" + tableId + '_' + fieldId + '_' + primaryKey).html('');
      } else {
        $("#tableVoteWarning_" + tableId + '_' + fieldId + '_' + primaryKey).html(status);
      }
    });
  });
}

function tableSortTriggers(startingPoint) {
//  $("table.sortable", startingPoint).tablesorter();
  $("#npcVSBallistaeReport").tablesorter({ debug: false });
}

function removeWrapper(s, sWrap) {
  s = s.replace(/(\n|\r)+$/, '');
  var iWrapSize = sWrap.length;
  var iTo = s.length - iWrapSize - 3;

  var openTag = '<' + sWrap + '>';
  var closeTag = '</' + sWrap + '>';

  if (openTag == s.substring(0, openTag.length) && closeTag == s.substring(iTo)) {
    return (s.substring(openTag.length, s.length - closeTag.length));
  } else {
    return ("No Match");
  }
}

function applyJqueryTriggers(startingPoint) {
  //For "mini" tinymce editors
  $('textarea.tinymcemini', startingPoint).tinymce({
    // Location of TinyMCE script

    script_url : getpathtoxml() + 'jquery/tinymce/tiny_mce.js',

    // General options
    theme : "advanced",
    plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",

    // Theme options
    //theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
    //theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
    //theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
    //theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
    theme_advanced_toolbar_location : "top",
    theme_advanced_toolbar_align : "left",
    theme_advanced_statusbar_location : "bottom",
    theme_advanced_resizing : false

    // Example content CSS (should be your site CSS)
    //content_css : "css/styles.css",

    // Drop lists for link/image/media/template dialogs
    //template_external_list_url : "lists/template_list.js",
    //external_link_list_url : "lists/link_list.js",
    //external_image_list_url : "lists/image_list.js",
    //media_external_list_url : "lists/media_list.js",
  });

  //For full size tinymce editors
  $('textarea.tinymce', startingPoint).tinymce({
    // Location of TinyMCE script

    script_url : getpathtoxml() + 'jquery/tinymce/tiny_mce.js',

    // General options
    theme : "advanced",
    plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",

    // Theme options
    theme_advanced_buttons1 : "newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,formatselect,fontselect,fontsizeselect",
    theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
    theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
    theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
    theme_advanced_toolbar_location : "top",
    theme_advanced_toolbar_align : "left",
    theme_advanced_statusbar_location : "bottom",
    theme_advanced_resizing : false,

    // Example content CSS (should be your site CSS)
    //content_css : "css/styles.css",

    // Drop lists for link/image/media/template dialogs
    //template_external_list_url : "lists/template_list.js",
    //external_link_list_url : "lists/link_list.js",
    //external_image_list_url : "lists/image_list.js",
    //media_external_list_url : "lists/media_list.js",
  });

	// For Nivo Slider
	$('.slider').nivoSlider({
		effect:'fade', //    *  sliceDown   * sliceDownLeft * sliceUp * sliceUpLeft * sliceUpDown * sliceUpDownLeft * fold * fade * random
		slices:15,
		animSpeed:500,
		pauseTime:6000,
		startSlide:0, //Set starting Slide (0 index)
		directionNav:true, //Next & Prev
		directionNavHide:true, //Only show on hover
		controlNav:true, //1,2,3...
		controlNavThumbs:true, //Use thumbnails for Control Nav
		controlNavThumbsFromRel: true,
		//controlNavThumbsSearch: '700x500', //Replace this with...
		//controlNavThumbsReplace: '64x64', //...this in thumb Image src
		keyboardNav:true, //Use left & right arrows
		pauseOnHover:true, //Stop animation while hovering
		manualAdvance:false, //Force manual transitions
		captionOpacity:0.8, //Universal caption opacity
		beforeChange: function(){},
		afterChange: function(){},
		slideshowEnd: function(){} //Triggers after all slides have been shown
	});

  // generate markup
  $("#pictureComment", startingPoint).append("Please rate: ");

  urlTriggers(startingPoint);

  requiredTriggers(startingPoint); 

  mediaVoteTriggers(startingPoint);

  tableVoteTriggers(startingPoint);
  
  tableSortTriggers(startingPoint);
	
	cropImageTriggers(startingPoint);

  // add markup to container and apply click handlers to anchors
  $(".phpLinkedData", startingPoint).click(function(e){
    // stop normal link click
    e.preventDefault();
    var idArray = this.id.split("_");

    var flags = idArray[1];

    if (flags & 1) {
      if (confirm("Are you sure you want to continue?")) {
      } else {
        //debug("Procedure Cancelled");
        return(0);
      }
    }

    var paramCount = idArray.length - 4
    var elementToUpdate = idArray[2];

    // build request
    myJsonQuery = { functionName: idArray[3] };
    //myJsonQuery['function'] = paramCount;
    myJsonQuery['paramcount'] = paramCount;

    var count = 0;
    for(loop = 1; loop <= paramCount;loop++) {
      count++;

      if (idArray[(count) +3].substring(0, 1) == "@") {
        var theFieldID = idArray[(count) + 3].substring(1);  
        var theField = document.getElementById(theFieldID);
        //debug("FIELD ID = " + theFieldID);

      if ((($('#' + theFieldID).attr('class') == 'tinymce')) || (($('#' + theFieldID).attr('class') == 'tinymcemini'))) {
        var value = $('#' + theFieldID).tinymce().getContent({format : 'text'});
        $('#' + theFieldID).tinymce().setContent('');
      } else {
        var value = theField.value;
      }

    value = value.replace("#", "%23");
    value = value.replace("&", "%26");

    myJsonQuery['param' + count] = value;
        theField.value = "";
      } else {
        myJsonQuery['param' + count] = idArray[(count) + 3];
      }
    }

    // send request
    $.post( getpathtoxml() + "webfiles/xml.php",  myJsonQuery, function(result) {
      // format and output result

      if (typeof XMLSerializer != "undefined") {
        var xmlString = (new XMLSerializer()).serializeToString(result);
      } else {
        var xmlString = result.xml;
      }

      //debug(xmlString);
      xmlString = xmlString.replace(/&amp;/g, '&');
      contents = removeWrapper(xmlString, 'content');

      $("#" + elementToUpdate).html(
        contents
      );

      element = document.getElementById(elementToUpdate);
      applyJqueryTriggers(element);

      //Table Edit
      preparetriggers(element, 'none')

      if (flags & 4) {
        window.location.reload(true);
      }
    });

    if (flags & 2) {
      tb_remove();
    }

  });
}
