/*
* WWW.DJMIKEMCCARTHY.COM
*
* file : utils.php
* author : SEconceptWeb.ca (Sébastien Éthier)
* last change : december 28, 2010
*
* */


    if (!window.console) console = {log: function() {}};

    function StringBuffer() {
        this.buffer = new Array();
    }

    StringBuffer.prototype.append = function append(string) {
    this.buffer.push(string);
    return this;
    };

    StringBuffer.prototype.toString = function toString() {
    return this.buffer.join("");
    };


    function stopDefault(event){
       if(event && event.preventDefault)
            event.preventDefault();
       else
            window.event.returnValue = true;


       return false; 
    }

/*
* Author : Simon Willison
* http://simonwillison.net/2004/May/26/addLoadEvent/
* Alternative : $(window)load(function(){}); from jQuery Dean Edward
* http://stackoverflow.com/questions/3980366/difference-between-addloadevent-and-function-load-of-jquery
* */
    function addLoadEvent(func) {
      var oldonload = window.onload;
      if (typeof window.onload != 'function') {
        window.onload = func;
      } else {
        window.onload = function() {
          if (oldonload) {
            oldonload();
          }
          func();
        }
      }
    }


    /* function init() {
        document.getElementById('file_upload_form').onsubmit=function() {
            document.getElementById('file_upload_form').target = 'upload_target'; //'upload_target' is the name of the iframe
            document.getElementById("upload_target").onload = uploadDone; //This function should be called when the iframe has compleated loading
            // That will happen when the file is completely uploaded and the server has returned the data we need.
            // to put this in jQuery .load
        }
    }*/

    /********************************************************************/
    var Uploader = (function(){

        //init variable
        var $formidObj;
        var type;
        var PATHIMAGEUPLOAD = "/image_uploads/";

        function attachEventSubmitToForm(settings){

                $formidObj = settings.formidObj || null;
                type = settings.type || null;

                //console.log("$formidObj.length=" + $formidObj.length);

                //addEventLister jQuery onsubmit
                $formidObj.submit(function(evt, isFileSystem){
                    //evt.stopPropagation();
                    if(!isFileSystem) isFileSystem = false;

                    if(isFileSystem)
                        $(this)[0].setAttribute('action','/snippets/upload.php?type=file');
                    else
                        $(this)[0].setAttribute('action','/snippets/upload.php?type=blob');

                    //console.log(">>> debut submit " + isFileSystem);
                    //evt.preventDefault();
                    var formid =  $(this).attr("id").match(/\d+$/);  //console.log("formid=" + formid);
                    var $iFrameCurrent;

                    if(formid == null)
                        $iFrameCurrent = $("#upload_target",this);
                    else
                        $iFrameCurrent = $("#upload_target_"+formid,this);

                    //console.log($iFrameCurrent);

                    $iFrameCurrent.empty();

                    if(formid == null)
                        $(this).attr("target","upload_target");
                    else
                        $(this).attr("target","upload_target_"+formid); //'upload_target'; //'upload_target' is the name of the iframe

                    if($iFrameCurrent.data("hasEventListener") != "true"){//simule hasEventLister like ActionScript -- prevent event bound
                        $iFrameCurrent.load(function(evt){ //This function should be called when the iframe has completed loading
                                $iFrameCurrent.data("hasEventListener","true");
                                //console.log(">>>load");
                                //console.log("isP="+evt.isPropagationStopped()); //.stopPropagation();
                                uploadDone.call(this);
                                //init to blob system

                           });
                    }
                    //$(this).get(0).submit();
                    //console.log(">>> fin submit " + isFileSystem);
                });

                //bind an addEventLister to the input[type=file]
                $("input[type='file']",$formidObj).bind("change",inputFileHandler);

        }

        //store a tmp file 
        function inputFileHandler(evt){
             //evt.stopPropagation();
                var $currentForm = $(evt.target).parent("form");
                //$currentForm[0].setAttribute('action','/snippets/upload.php?type=file');
                $currentForm.trigger("submit", ["true"]);
        }


        function uploadDone() { //Function will be called when iframe is loaded

            //console.log(">>> uploadDone");

            var $iframeObj = $(this) || null;

            //get iframe body
            var retrieveIframeBody = $iframeObj.contents().find("body").html();

            //alert(retrieveIframeBody);
            //alert(/^{|}$/.test(retrieveIframeBody));

            if(!/^{|}$/.test(retrieveIframeBody)){ //check if the answer a JSON style or HTML style
                //a HTML style
                //replace the old cover by image produced inside the iframe

               // $iframeObj.parents("form").prepend(retrieveIframeBody);
                $("img.mt-cover",$iframeObj.parents("form")).replaceWith(retrieveIframeBody);

                //$iframeObj.after(retrieveIframeBody);

                //$iframeObj.siblings("img.mt-cover").replaceWith(retrieveIframeBody);//ie seem to suck on this


            }else{
                //a JSON style
                var data = JSON.parse(retrieveIframeBody); //"); //Parse JSON // Read the below explanations before passing judgment on me

                if(data.success)
                { //Upload failed - show user the reason.
                    $iframeObj.siblings("div[id^='image_details_']").html("Success : " +  data.message);

                    if(data.file_name){
                        //alert(data.file_name);
                        $iframeObj.siblings("img.mt-cover").attr("src", PATHIMAGEUPLOAD.concat(data.file_name));
                    }
                }

                if(data.failure)
                { //Upload failed - show user the reason.
                    $iframeObj.siblings("div[id^='image_details_']").html("Error : " +  data.message);
                }
            }
        }

        function getiFrameBodyHTML(){
            //this means the iFrame
            return $(this).contents().find("body").html();
        }

        return{//public method
            initialize : function(settings){
                if(typeof settings == 'undefined')  return;
                attachEventSubmitToForm(settings);
            }
        }

    })();

    /*******************************************************************************************************************/

        // alert("uploadDone");
        // var ret = frames['upload_target'].document.getElementsByTagName("body")[0].innerHTML;

     /*
    alert(ret);

        var data = eval("("+ret+")"); //Parse JSON // Read the below explanations before passing judgment on me

        alert("uploadDone" + data.success);

        if(data.success) { //This part happens when the image gets uploaded.
            console.log("sucessAAA");
           // document.getElementById("image_details").innerHTML = "<img src='{$URL}image_uploads/" + data.file_name + "' /><br />Size: " + data.size + " KB";

        }*/
/*
        if(data.failure) { //Upload failed - show user the reason.
            //alert("Upload Failed: " + data.failure);
            console.log("failure");
            document.getElementById("image_details").innerHTML = "Upload Failed: " + data.failure;
        }
        */


      /*  document.getElementById('file_upload_form').onsubmit=function() {
            document.getElementById('file_upload_form').target = 'upload_target'; //'upload_target' is the name of the iframe
            document.getElementById("upload_target").onload = uploadDone; //This function should be called when the iframe has compleated loading
			// That will happen when the file is completely uploaded and the server has returned the data we need.
            // to put this in jQuery .load
        }*/

/*
    function uploadDone() { //Function will be called when iframe is loaded

       // alert("uploadDone");
        var ret = frames['upload_target'].document.getElementsByTagName("body")[0].innerHTML;
        alert(ret);

        var data = eval("("+ret+")"); //Parse JSON // Read the below explanations before passing judgment on me

        alert("uploadDone" + data.success);

        if(data.success) { //This part happens when the image gets uploaded.
            console.log("sucessAAA");
           // document.getElementById("image_details").innerHTML = "<img src='{$URL}image_uploads/" + data.file_name + "' /><br />Size: " + data.size + " KB";

        }
        else if(data.failure) { //Upload failed - show user the reason.
            //alert("Upload Failed: " + data.failure);
            console.log("failure");
            document.getElementById("image_details").innerHTML = "Upload Failed: " + data.failure;
        }
    }*/
