﻿//flashupload helper
var flashupload = {};
var actions = {};
var alertbeforeredirect = false;

$.ajaxSetup( { type: "POST" } ); //set the default ajax submits to POST

$().ready(function () {
    //setup default form behaviors via classes 
    $('.ajaxsubmit').click( function() { $(this).ajaxsubmit(); return false; } );
    $('.ajaxtoggle').click( function() { $(this).ajaxtoggle(); } );        {postvalue:'photoalbum_id'}
    $('.ajaxselect').click( function() { $(this).ajaxtoggle(); } );        
});


//jquery plugin versions
(function($){  
     $.fn.ajaxselect = function(options) {  
      
    defaultsettings = { action : $('body').find('.selectlink:first').html(),
                        successfunction : function(msg){ $('.inlinemessage').html(msg); },
                        id : $(this).parent().parent().attr('title'),
                        postvalue : 'newvalue'
                      } //end of defaultsettings
  
     var options = $.extend(defaultsettings, options);  
  
     //console.log($(this).parent()); console.log(caller); console.log(this); console.log(options);
     
        $.ajax({
            type: "POST",
            url: options.action + "/" + options.id,
            data: options.postvalue+"="+$(this).val(),
            success: options.successfunction
        });
        
         return true;
  
    };  
   })(jQuery);  



(function($){  
     $.fn.ajaxsubmit = function(options) {  
      
    defaultsettings = { action : $(this).parent().find('.hiddenlink:first').html(), /* post url - if there is no defined url to post to, look for .hiddenlink div */
                        targetcontainer : $(this).parent(),                         /* form container - if no target form or div, uses parent container */
                        clearinputs : true, 
                        successfunction : function(msg){                            /* if no HREF url, then fire this function to show response as an alert or inline message */
                                            if ( $('.inlinemessage').length > 0 )  
                                                $('.inlinemessage').html(msg);
                                            else alert(msg);  },  
                        failfunction : function(){},
                        validate : true,
                        jsonreturn : false,
                        injectkey : 'none',
                        injectval : 'none'               
                       }

     //if link is not # ( and json hasn't redirected them ) then redirect after success to the HREF (otherwise will just use regular successfuction )
     //only a overriden successfunction will stop a redirect
     if ( $(this).attr('href') != "#" )
     {
        //save redirect url that was stored in href       
        redirecturl = $(this).attr('href');
        defaultsettings.successfunction = function(msg) { 
            //if successful redirect to stored href value
            //console.log(msg);
            if (alertbeforeredirect == true) {  if (confirm(redirecturl)) { window.location = redirecturl; }  }
            else window.location = redirecturl; 
            }
     }
     
     
     //if Json return is detected switch to parsing JSON return for functionality, unless overriden by a custom successfunction
     if ( options.jsonreturn == true )
     {
           
        defaultsettings.successfunction = function(msg) { 
            var returno = eval( '(' + msg + ')' ); 
            /* alert(returnvalue.success); */
            if (returno.success) {  
                                    if ( returno.redirecturl != null ) 
                                    { window.location = returno.redirecturl; }
                                    else
                                    {
                                     //alert message (since no redirect)
                                     if ( $('.inlinemessage').length > 0 ) 
                                      { 
                                                    $.scrollTo(1,{onAfter:function(){ 
                                                        $('.inlinemessage').html(returno.message).fadeIn("slow");
                                                        setTimeout(function(){ $('.inlinemessage').fadeOut("slow"); } ,2000);  
                                                        
                                                        }});
                                                    

                                      }
                                      else  { alert(returno.message); }  
                                    }//end of no redirecturl 
                                 }//end of if success
            else { 
                    //for now alert whats wrong
                    if (returno.message != null) {           
                                                if ( $('.inlinemessage').length > 0 ) { 
                                                    
                                                    $.scrollTo(1,{onAfter:function(){ 
                                                        $('.inlinemessage').html(returno.message).fadeIn("slow");
                                                        setTimeout(function(){ $('.inlinemessage').fadeOut("slow"); } ,2000);  
                                                        
                                                        }});
                                                    
                                                    
                                                    
                                                }
                                            else  { alert(returno.message); }  
                              } else { alert("BlogPub Ajax Error"); };  
                  
                  
                 //   if (console) console.log(returno);
                 
                 
                 } //end of else json.success = false 
            };    
     }
     
    //override any settings, including href successfuction 
    var options = $.extend(defaultsettings, options);    
    
    
    if ( options.targetcontainer.iscontainervalid() || options.validate != true )
    {
        //if there is a injected input value add it
        var inject = (options.injectkey != 'none') ?  '&' + options.injectkey + '=' + options.injectval : '';
    
        $.ajax({
            type: "POST",
            url: options.action,
            data: options.targetcontainer.find(':input').fieldSerialize() + inject,
            success: options.successfunction
        });
        
        if (options.clearinputs)
            options.targetcontainer.find(':input').clearInputs();
            
         return true;
    }
    else
    {
        //fire off failfunction
        options.failfunction();
        
        return false;
    }
       
    };  
   })(jQuery);  




(function($){  
     $.fn.ajaxtoggle = function(options) {  
      
     //add functionality to check for linkname (container) stored in selects name
      
    defaultsettings = { action : $('body').find('.togglelink:first').html(),
                        successfunction : function(msg){ $('.inlinemessage').html(msg); },
                        id : $(this).parent().parent().attr('title'),
                        postvalue : 'ischecked'
                      } //end of defaultsettings
  
     var options = $.extend(defaultsettings, options);  
  
     //console.log($(this).parent()); console.log(caller); console.log(this); console.log(options);
     
        $.ajax({
            type: "POST",
            url: options.action + "/" + options.id,
            data: options.postvalue + "=" + $(this).is(':checked'),
            success: options.successfunction
        });
        
         return true;
  
    };  
   })(jQuery);  



//checks all children in element and highlights errors (based on .req and .reqemail classes)
(function($){  
     $.fn.iscontainervalid = function(options) {  
      
        defaultsettings = { errorclass : 'inputerror' };
  
        var options = $.extend(defaultsettings, options);  
  
  
    var isvalid = true;
    $(this).find('.req').removeClass(options.errorclass).each( function() {  if ( formhelper.isempty(this.value) ) { $(this).addClass(options.errorclass); isvalid = false;  }   } );
    $(this).find('.reqemail').removeClass(options.errorclass).each( function() {  if ( !formhelper.isemail(this.value) && !formhelper.isempty(this.value) ) { $(this).addClass(options.errorclass); isvalid = false;  }   } );

    return isvalid;



    };  
   })(jQuery);  

//checks first class then id for target
(function($){  
     $.fn.classorid = function( name ) {  
      
        var classname = "." + name;
        var idname = "#" + name;
      
        return ( $( classname ).length > 0 ) ? classname : ($( idname ).length > 0) ? idname : classname; 
      
      
      /*
        if  ( $( classname ).length > 0 )
        {
            return classname
        }
        else if (  $( idname ).length > 0 )
        {
            return idname
        }
        else return classname; //can't find either, so default to using the classname
        */
    };  
   })(jQuery);        


//formhelper namespace
var formhelper = {};


//caller is mandatory and is always 'this'
formhelper.ajaxsubmit = function (caller, usersettings )// successfunction,action,validate,targetcontainer)
{
    //default settings
    defaultsettings = { action : $(caller).parent().find('.hiddenlink:first').html(),
                        targetcontainer : $(caller).parent(),
                        clearinputs : true,
                        successfunction : function(msg){ $('.inlinemessage').html(msg); },
                        failfunction : function(){},
                        validate : true                
                       }
    
    //merge default settings with user passed settings      
    var settings = $.extend(defaultsettings, usersettings);      

    // console.log(settings); console.log(targetcontainer); console.log(validate); console.log(action); */  
    //console.log(settings); 
    // if all mandatory fields are correctly filled out or our validation is off
    if ( formhelper.iscontainervalid(settings.targetcontainer) || settings.validate != true )
    {
        $.ajax({
            type: "POST",
            url: settings.action,
            data: settings.targetcontainer.find(':input').fieldSerialize(),
            success: settings.successfunction
        });
        
        //reset input forms if clearinputs flag is true
        if (settings.clearinputs)
            settings.targetcontainer.find(':input').clearInputs();
    }
    else
    {
        //fire off function for validation test failing
        settings.failfunction();
    }
    
    return false;
}


formhelper.isurl = function (str)
{
	if(formhelper.isempty(str)) return false;
	var re = /^(file|http):\/\/[\S+\.]+$/i
	return re.test(str);
}
			
formhelper.trim = function(str)
{
	var thisStr = str.toString();
	var re = /\s/g
	if(thisStr.search(re) != -1){
		thisStr = thisStr.replace(re, '');
	}
	return thisStr;
}

formhelper.isempty =  function(str){
	var text = formhelper.trim(str);
	return ( text == null || text.length == 0 ) ? true : false ;
}

formhelper.isemail = function(email)
{
	
	var re = /^[^\s()<>@,;:\/]+@\w[\w\.-]+\.[a-z]{2,}$/i
	var isEmail = re.test(email);
	return isEmail;

}
		
//formhelper.iscontainervalid  adds/removes validation errors , returns true if no errors are found 
formhelper.iscontainervalid = function ( formcontainer )
{
    var isvalid = true;
    $(formcontainer).find('.req').removeClass("inputerror").each( function() {  if ( formhelper.isempty(this.value) ) { $(this).addClass("inputerror"); isvalid = false;  }   } );
    $(formcontainer).find('.reqemail').removeClass("inputerror").each( function() {  if ( !formhelper.isemail(this.value) ) { $(this).addClass("inputerror"); isvalid = false;  }   } );

    return isvalid;
}		

//formhelper.iscontainervalid  adds/removes validation errors , returns true if no errors are found 
formhelper.isjcontainervalid = function ( formcontainer )
{
    var isvalid = true;
    formcontainer.find('.req').removeClass("inputerror").each( function() {  if ( formhelper.isempty(this.value) ) { $(this).addClass("inputerror"); isvalid = false;  }   } );
    formcontainer.find('.reqemail').removeClass("inputerror").each( function() {  if ( !formhelper.isemail(this.value) ) { $(this).addClass("inputerror"); isvalid = false;  }   } );

    return isvalid;
}	

/*
(function($){
 $.fn.checkinputs = function(options) {
    
  var defaults = {
   length: 300,
   minTrail: 20,
   moreText: "more",
   lessText: "less",
   ellipsisText: "..."
  };
  
  var options = $.extend(defaults, options);
    
  return this.each(function() {
   obj = $(this);
   
    $(this).find('.req').removeClass("inputerror").each( function() {  if ( formhelper.isempty(this.value) ) { $(this).addClass("inputerror"); isvalid = false;  }   } );
    $(this).find('.reqemail').removeClass("inputerror").each( function() {  if ( !formhelper.isemail(this.value) ) { $(this).addClass("inputerror"); isvalid = false;  }   } );
   
  });
 };
})(jQuery);
*/










/**
 * Serializes all field elements in the jQuery object into a query string.
 * This method will return a string in the format: name1=value1&amp;name2=value2
 */
$.fn.fieldSerialize = function(successful) {
    var a = [];
    this.each(function() {
        var n = this.name;
        if (!n) return;
        var v = $.fieldValue(this, successful);
        if (v && v.constructor == Array) {
            for (var i=0,max=v.length; i < max; i++)
                a.push({name: n, value: v[i]});
        }
        else if (v !== null && typeof v != 'undefined')
            a.push({name: this.name, value: v});
    });
    //hand off to jQuery.param for proper encoding
    return $.param(a);
};

/**
 * Returns the value(s) of the element in the matched set.  For example, consider the following form:
 *
 *  <form><fieldset>
 *      <input name="A" type="text" />
 *      <input name="A" type="text" />
 *      <input name="B" type="checkbox" value="B1" />
 *      <input name="B" type="checkbox" value="B2"/>
 *      <input name="C" type="radio" value="C1" />
 *      <input name="C" type="radio" value="C2" />
 *  </fieldset></form>
 *
 *  var v = $(':text').fieldValue();
 *  // if no values are entered into the text inputs
 *  v == ['','']
 *  // if values entered into the text inputs are 'foo' and 'bar'
 *  v == ['foo','bar']
 *
 *  var v = $(':checkbox').fieldValue();
 *  // if neither checkbox is checked
 *  v === undefined
 *  // if both checkboxes are checked
 *  v == ['B1', 'B2']
 *
 *  var v = $(':radio').fieldValue();
 *  // if neither radio is checked
 *  v === undefined
 *  // if first radio is checked
 *  v == ['C1']
 *
 * The successful argument controls whether or not the field element must be 'successful'
 * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
 * The default value of the successful argument is true.  If this value is false the value(s)
 * for each element is returned.
 *
 * Note: This method *always* returns an array.  If no valid value can be determined the
 *       array will be empty, otherwise it will contain one or more values.
 */
$.fn.fieldValue = function(successful) {
    for (var val=[], i=0, max=this.length; i < max; i++) {
        var el = this[i];
        var v = $.fieldValue(el, successful);
        if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length))
            continue;
        v.constructor == Array ? $.merge(val, v) : val.push(v);
    }
    return val;
};

/**
 * Returns the value of the field element.
 */
$.fieldValue = function(el, successful) {
    var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
    if (typeof successful == 'undefined') successful = true;

    if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
        (t == 'checkbox' || t == 'radio') && !el.checked ||
        (t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
        tag == 'select' && el.selectedIndex == -1))
            return null;

    if (tag == 'select') {
        var index = el.selectedIndex;
        if (index < 0) return null;
        var a = [], ops = el.options;
        var one = (t == 'select-one');
        var max = (one ? index+1 : ops.length);
        for(var i=(one ? index : 0); i < max; i++) {
            var op = ops[i];
            if (op.selected) {
                // extra pain for IE...
                var v = $.browser.msie && !(op.attributes['value'].specified) ? op.text : op.value;
                if (one) return v;
                a.push(v);
            }
        }
        return a;
    }
    return el.value;
};

/**
 * Clears the selected form elements.
 */
$.fn.clearFields = $.fn.clearInputs = function() {
    return this.each(function() {
        var t = this.type, tag = this.tagName.toLowerCase();
        if (t == 'text' || t == 'password' || tag == 'textarea')
            this.value = '';
        else if (t == 'checkbox' || t == 'radio')
            this.checked = false;
        else if (tag == 'select')
            this.selectedIndex = -1;
    });
};

/**
 * Resets the form data.  Causes all form elements to be reset to their original value.
 */
$.fn.resetForm = function() {
    return this.each(function() {
        // guard against an input with the name of 'reset'
        // note that IE reports the reset function as an 'object'
        if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
            this.reset();
    });
};
