YAHOO.namespace("sbf");

String.prototype.endsWith = function(str)
{
    return (this.match(str+"$")==str)
}

YAHOO.sbf.clearForm = function(formname)
{
    formname.reset();
}

YAHOO.sbf.CallbackSuccessReload = function(o)
{
    alert(o.responseText);
    if(o.responseText !== undefined)
    {
        var result = o.responseText.parseJSON();
        if (result.sb.result == "ok")
        {
            window.location.reload();
        }
        else
        {
            myReason = result.sb.message;
            alert(myReason);
        }
    }
};

YAHOO.sbf.CallbackFail = function(o)
{
    alert("service call failed");
};

YAHOO.sbf.plainTextCheck = function()
{
    alert(YAHOO.sbf.formElement.value);
    return false;
};

YAHOO.sbf.jsonservicecall = function(service, json, callback)
{
    /*
     * Check if the form validated
     */
    /*
    var form_check = json.parseJSON();
    if (form_check.sb.data.form_fail != undefined)
	{
	    alert(form_check.sb.data.form_fail);
	    return;
	}
    */
    if (!service.endsWith("/"))
    {
        service += "/";
    }
    service += "service.php";
    var postData = "format=json&data=" + escape(json);
    var myRequest = YAHOO.util.Connect.asyncRequest('POST', service, callback, postData);
}

YAHOO.sbf.getJSONFromDocument = function()
{
    var json = "{\"data\": {";
    var count =0;
    for (var i=0;i<document.forms.length;i++)
    {
        var form = document.forms[i];
        if (count > 0)
        {
            json += ",";
        }
        var formname = form.name;
        if (formname == "")
        {
            formname = form.id;
        }
        json += formname.toJSONString() + ": ";
        json += YAHOO.sbf.getJSONFromForm(form);
        count++;
    }
    json += "} }";
    return json;
}

YAHOO.sbf.getJSONFromForm = function(form)
{
    var json = "{";
    json += YAHOO.sbf.getOpenJSONFromForm(form);
    json += "}";
    return json;
}

YAHOO.sbf.getOpenJSONFromForm = function(form)
{
    var json = "";
    var count =0;
    for (var i=0;i<form.length;i++)
    {
        var current = form.elements[i];
        if ((current.name != "") || (current.type != undefined))
        {
            if (current.type == "hidden" || current.type == "text" || current.type == "password" || current.type == "textarea")
            {
		for (var j=0;j<current.attributes.length;j++)
		    {
			if (current.attributes[j].name == "validator")
			    {
				YAHOO.sbf.formElement = current;
				var validator = current.attributes[j].value;
				if (eval("typeof " + validator + " == 'function'"))
				    {
					validator += "()";
					var check = eval(validator);
					if (!check)
					    {
						var span_text = form.name + "_" + current.name;
						json = "{ \"form_fail\": \""+document.getElementById(span_text).innerHTML+"\"}";
						return json;
					    }
				    }
			    }
		    }
                if (count > 0)
                {
                    json += ",";
                }
                json += current.name.toJSONString() + ":" + current.value.toJSONString();
                count++;
            }
            else if (current.type == "checkbox" || current.type == "radio")
            {
                if (current == document.getElementsByName(current.name)[0])
                {
                    if (count > 0)
                    {
                        json += ",";
                    }
                    json += current.name.toJSONString() + ":" + YAHOO.sbf.getCheckboxValues(document.getElementsByName(current.name)).toJSONString();
                    count++;
                }
            }
            else if (current.type == "select-one" || current.type == "select-multiple")
            {
                if (count > 0)
                {
                    json += ",";
                }
                json += current.name.toJSONString() + ":" + YAHOO.sbf.getManyOpts(current).toJSONString();
                count++;
            }
            else if (current.type == "submit")
            {
                if (count > 0)
                {
                    json += ",";
                }
                json += current.name.toJSONString() + ":" + current.value.toJSONString();
                count++;
            }
	    else if (current.type == "fieldset")
		{
		    alert("Fieldset");
		    // pass
		}
            else
            {
                //alert(current.name + " " + current.type);
            }
        }
    }
    return json;
};


YAHOO.sbf.escapeJSON = function(contentString)
{
    return contentString.toJSONString();
}

YAHOO.sbf.getOneOpt = function(myOpts) {
  var myVal = "";
  if (myOpts.selectedIndex !== -1) {
    myVal = myOpts[myOpts.selectedIndex].value;
  }
  return myVal;
};

YAHOO.sbf.getOneOptAndValue = function(myOpts) {
  var myVal = "";
  if (myOpts.selectedIndex !== -1) {
    myVal = myOpts[myOpts.selectedIndex];
  }
  return myVal;
};

YAHOO.sbf.getManyOpts = function(myOpts)
{
  var myVal = "";
  var output = "";
  var j= 0;
  for (i=0; i<myOpts.length; i++)
  {
    if (myOpts[i].selected)
    {
      if (j !== 0)
      {
        myVal += ",";
      }
      myVal += myOpts[i].value;
      j++;
    }
  }
  return myVal;
};

YAHOO.sbf.getManyOptsAndValues = function(myOpts) {
  var myVal = new Array();

  for (i=0; i<myOpts.length; i++) {
    if (myOpts[i].selected === true) {
      myLen = myVal.length;
      myVal[myLen] = new Array();
      myVal[myLen][0] = myOpts[i].value;
      myVal[myLen][1] = myOpts[i].text;
    }
  }
  return myVal;
};

YAHOO.sbf.getSelectList = function(myOpts)
{
  var myVal = "";
  var output = "";
  var j = 0;
  for (i=0; i<myOpts.length; i++)
  {
    if (j !== 0)
    {
      myVal += ",";
    }
    myVal += myOpts[i].value;
    j++;
  }
  return myVal;
};

YAHOO.sbf.getCheckboxValues = function(myOpts)
{
  var myVal = "";
  var first = true;
  if (myOpts)
  {
    if (typeof myOpts.length != 'undefined')
    {
      for (i = 0; i < myOpts.length; i++)
      {
        if (myOpts[i].checked)
        {
          if (!first)
          {
            myVal += ',';
          }
          myVal += myOpts[i].value;
          first = false;
        }
      }
    }
    else
    {
      myVal = myOpts.value;
    }
  }
  return myVal;
}

YAHOO.sbf.findChecked = function(myOpts) {
    var myVal = "";

    var j= 0;
    for (i=0; i<myOpts.length; i++) {
    if (myOpts[i].checked === true) {
        if (j !== 0) {
        myVal += ",";
        }
        myVal += myOpts[i].value;
        j++;
    }
  }
  return myVal;
};

YAHOO.sbf.isChecked = function(myOpts, testValue) {
  var myVal = false;
    for (i=0; i<myOpts.length; i++) {
    if (myOpts[i].value === testValue) {
          myVal = myOpts[i].checked;
    }
    }
  return myVal;
};

YAHOO.sbf.formatDBDate = function(date)
{
    var dateArray = date.split("-");
    var myVal = dateArray[2] + "/" + dateArray[1] + "/" + dateArray[0];
    return myVal;
};

YAHOO.sbf.formatDBTimeStripSeconds = function(time)
{
    var timeArray = time.split(":");
    var myVal = timeArray[0] + ":" + timeArray[1];
    return myVal;
};

YAHOO.sbf.getDate = function(date)
{
    var dateArray = date.split("/");
    var myVal = dateArray[2] + "-" + dateArray[1] + "-" + dateArray[0];
    return myVal;
};

YAHOO.sbf.getText = function(o)
{
  if (o.innerText)
    {
      ret_string = o.innerText;
    }
  else if (o.textContent)
    {
      ret_string = o.textContent;
    }
  else
    {
      ret_string = "Unsupported Browser";
    }

  return ret_string;
};

YAHOO.sbf.addToBreadCrumb = function()
{
    var ming = 1;
};

var keyStr = "ABCDEFGHIJKLMNOP" +
    "QRSTUVWXYZabcdef" +
    "ghijklmnopqrstuv" +
    "wxyz0123456789+/" +
    "=";

YAHOO.sbf.encode64 = function(input)
{
    input = escape(input);
    var output = "";
    var chr1, chr2, chr3 = "";
    var enc1, enc2, enc3, enc4 = "";
    var i = 0;

    do {
        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);

        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;

        if (isNaN(chr2))
	    {
		enc3 = enc4 = 64;
	    }
	else if (isNaN(chr3))
	    {
		enc4 = 64;
	    }

        output = output +
	    keyStr.charAt(enc1) +
	    keyStr.charAt(enc2) +
	    keyStr.charAt(enc3) +
	    keyStr.charAt(enc4);
        chr1 = chr2 = chr3 = "";
        enc1 = enc2 = enc3 = enc4 = "";
    } while (i < input.length);

    return output;
};

YAHOO.sbf.decode64 = function(input)
{
    var output = "";
    var chr1, chr2, chr3 = "";
    var enc1, enc2, enc3, enc4 = "";
    var i = 0;

    // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
    var base64test = /[^A-Za-z0-9\+\/\=]/g;
    if (base64test.exec(input)) {
        alert("There were invalid base64 characters in the input text.\n" +
              "Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\n" +
              "Expect errors in decoding.");
    }
    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

    do {
        enc1 = keyStr.indexOf(input.charAt(i++));
        enc2 = keyStr.indexOf(input.charAt(i++));
        enc3 = keyStr.indexOf(input.charAt(i++));
        enc4 = keyStr.indexOf(input.charAt(i++));

        chr1 = (enc1 << 2) | (enc2 >> 4);
        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
        chr3 = ((enc3 & 3) << 6) | enc4;

        output = output + String.fromCharCode(chr1);

        if (enc3 != 64)
	    {
		output = output + String.fromCharCode(chr2);
	    }
        if (enc4 != 64)
	    {
		output = output + String.fromCharCode(chr3);
	    }

        chr1 = chr2 = chr3 = "";
        enc1 = enc2 = enc3 = enc4 = "";

    } while (i < input.length);

    return unescape(output);
}

/*
yuiImgUploader
variables:
 rte: The YAHOO.widget.Editor instance
 upload_url: the url to post the file to
 upload_image_name: the name of the post parameter to send the file as

Your server must handle the posted image.  You must return a JSON object
with the result url that the image can be viewed at on your server.  If
the upload fails, you can return an error message.  For successful
uploads, the status must be set to UPLOADED.  All other status messages,
or the lack of a status message is interpreted as an error.  IE will
try to open a new document window when the response is returned if your
content-type header on your response is not set to 'text/javascript'

Example Success:
{status:'UPLOADED', image_url:'/somedirectory/filename'}
Example Failure:
{status:'We only allow JPEG Images.'}

*/

YAHOO.sbf.yuiImgUploader = function(rte, editor_name, upload_url, upload_image_name)
{
    // customize the editor img button

    YAHOO.log( "Adding Click Listener" ,'debug');
    rte.addListener('toolbarLoaded',function()
{
    rte.toolbar.addListener ( 'insertimageClick', function(o) {
	    try {
		var imgPanel=new YAHOO.util.Element(editor_name + '-panel');
		imgPanel.on ( 'contentReady', function() {
			try {
			    var Dom=YAHOO.util.Dom;

			    if (! Dom.get(editor_name + '_insertimage_upload'))
				{
				    var label=document.createElement('label');
				    label.innerHTML='<strong>Upload:</strong>'+
					'<input type="file" id="' +
					editor_name + '_insertimage_upload" name="'+upload_image_name+
					'" size="10" style="width: 300px" />'+
					'</label>';

				    var img_elem=Dom.get(editor_name + '_insertimage_url');
				    Dom.getAncestorByTagName(img_elem, 'form').encoding = 'multipart/form-data';

				    Dom.insertAfter(
						    label,
						    img_elem.parentNode);

				    YAHOO.util.Event.on ( editor_name + '_insertimage_upload', 'change', function(ev) {
					    YAHOO.util.Event.stopEvent(ev); // no default click action
					    YAHOO.util.Connect.setForm ( img_elem.form, true, true );
					    var c=YAHOO.util.Connect.asyncRequest(
										  'POST', upload_url, {
										      upload:function(r){
											  try {
											      // strip pre tags if they got added somehow
											      resp=r.responseText.replace( /<pre>/i, '').replace ( /<\/pre>/i, '');
											      var o=eval('('+resp+')');
											      if (o.status=='UPLOADED') {
												  Dom.get(editor_name + '_insertimage_upload').value='';
												  Dom.get(editor_name + '_insertimage_url').value=o.image_url;
												  // tell the image panel the url changed
												  // hack instead of fireEvent('blur')
												  // which for some reason isn't working
												  Dom.get(editor_name + '_insertimage_url').focus();
												  Dom.get(editor_name + '_insertimage_upload').focus();
											      } else {
												  alert ( "Upload Failed: "+o.status );
											      }

											  } catch ( eee ) {
											      YAHOO.log( eee.message, 'error' );
											  }
										      }
										  }
										  );
					    return false;
					});
				}
			}
			catch ( ee ) { YAHOO.log( ee.message, 'error' ); }

		    });
	    } catch ( e ) {
		YAHOO.log( e.message, 'error' );
	    }
	});
});

};

