// JavaScript Document
// show_message - using div element as place holder to show message of type error or success
(function($){

        //Transition
        $.fn.transition_list = function(options){
        	_parent = this; 
            var settings = {};
            settings = $.extend({},settings,options); 				
			
			$('li',this).hide(); 
			var list_count = $('li','.carousel').length;
 
            var t;
            var _next = 0;
            var _prev = list_count-1;

            $('li:eq(0)',_parent).show();

            $('ul li',_parent).mouseover(function(){
                 clearTimeout(t)
            });

            $('ul li',_parent).mouseout(function(){ 
                start();
            });

			function show_next(prev,next){
                 
				_next = next;
				$('li:eq('+prev+')',_parent).hide();
				$('li:eq('+_next+')',_parent).fadeIn();

				_prev = _next;  
				_next++;
                
				if(_next>=list_count){
					_next=0;
				}
                start();
				
			}
            function start(){
                t = setTimeout(function(){show_next(_prev,_next)},6000);
            }
            
			start();
                        

    }
     
    
    
	$.fn.show_message = function(options){
		_parent = this; 
		var settings = { 
						 header:"",
						 message: "",
					     duration:0,
						 type:'error',
                         append:false
					   };
		settings = $.extend({},settings,options);
        
        if(settings.append==false){
            $(".msg_hnd",this).remove();
        }
        
 		var hmtl = "";
			if( settings.type == 'error' ){
				color = {bg:'#F24242','border':'#C00','text':'#FFF'};
			}else if( settings.type == 'requesting' ){
				color = {bg:'#FFFD85','border':'#FFD22B','text':'#696565'};
			}else if( settings.type == 'info' ){
				color = {bg:'#F6FF6B','border':'#FFD22B','text':'#696565'};
			}else{
				color = {bg:'#2B86CA','border':'#144077','text':'#FFF'};
			}
			hmtl	=	 '<div class="msg_hnd" style="padding:0px;margin:0px" >';
			hmtl	+=	 '<ul style="padding:0px;list-style:none;background:'+ color.bg +';border-top:1px solid '+ color.border +';border-bottom:1px solid '+ color.border +'">';
			if( settings.header == "" ){
				hmtl	+=	 '<li id="message_content" style="padding-left:10px;color:'+color.text+';font-size:13px">'+ settings.message +'</li>';
			}else{
				hmtl	+=	 '<table width="100%" align="center" height="60" border="0" cellpadding="0" cellspacing="0">';
				hmtl	+=	 '<tr>';
				hmtl	+=	 '<td><div class="componentheading" style="font-size:16px;color:'+color.text+'"  >&nbsp;&nbsp;'+ settings.header +'</div></td>';
				hmtl	+=	 '</tr>';
				hmtl	+=	 '<tr>';
				hmtl	+=	 '	<td><div class="componentheading" style="font-size:12px;font-weight:normal;color:'+color.text+';padding-left:20px"  >'+ settings.message +'</div></td>';
				hmtl	+=	 ' </tr>';
				hmtl	+=	 '</table>';
			}
			hmtl	+=	 '</ul>';
			hmtl	+=	 '</div>';
		
        $(hmtl).appendTo(this).fadeIn();
        $(this).show();
        if(settings.duration!=0){
            $('.msg_hnd',_parent).each(function(){  
                var _this = this;
                setTimeout( function(){ $(_this).fadeOut().remove(); }, settings.duration);
            }) 
		}
	}
	$.fn.validateform = function(option){
        $(".required",this).unbind('blur'); 
        $(".required",this).unbind('focus'); 
        $(".required",this).blur(function(){ 
            if(check_required(null,null,this)){
                $(this).css("background","#F24242");  
            }else{
                $(this).css("background","#FFFFFF");  
            }
        });
        
        $(".valid_email",this).blur(function(){ 
            if(check_email(null,null,this)){
                $(this).css("background","#F24242");  
            }else{
                $(this).css("background","#FFFFFF");  
            }
        });
        
        $(".required,.valid_email",this).focus(function(){ 
                $(this).css("background","#FFFFFF"); 
        });
        var _focus = false;
        var required_error = false;
        var email_error = false;
        function check_required(count,list_elem, single_elem){ 
            var _elem = null;
            var _single = false;
            if( count==null){
                _elem = single_elem;
                _single = true;
            }else{
                _elem = list_elem;
            } 
            if(_elem==null){
                return false;
            }
            if( $.trim($(_elem).val()) == '' ){
                required_error = true;
                if(_single){ 
                    return true;
                }
				$(_elem).css("background","#F24242");  
				 if(!_focus){
					 $(_elem).focus();
					 _focus = true;
				 } 
			}else{
			     if(_single){
                    return false;
                }
			}  
        }
        function check_email(count,list_elem, single_elem){ 
            var _elem = null;
            var _single = false;
            if( count==null){
                _elem = single_elem;
                _single = true;
            }else{
                _elem = list_elem;
            } 
            if(_elem==null){
                return false;
            }
            if( $.trim($(_elem).val()) == '' ){
                return false;
            }
            validRegExp = /^[^@]+@[^@]+.[a-z]{2,}$/i;  
            if( $(_elem).val().search(validRegExp) == -1 ){
                email_error = true;
                if(_single){ 
                    return true;
                }
				$(_elem).css("background","#F24242");  
				 if(!_focus){
					 $(_elem).focus();
					 _focus = true;
				 } 
			}else{
			     if(_single){
                    return false;
                }
			}  
        } 
        if(option=='init'){
            return true; 
        }
        $(".required",this).each(check_required); 
        $(".valid_email",this).each(check_email); 
        this.required_error = required_error;
        this.email_error = email_error;
        return this;
	}
    
	$.fn.myForm = function(options){
	   
            
			var _form = this;
			var settings = { action:null,
                             dataType:'json',
							 done: null,
							 loading:loading,
                             message_holder:'response_message',
                             hidecontrol:null,
                             init_hide:false
						   };

			settings = $.extend({},settings,options);
            $(this).validateform('init');
			var id = $(this).attr('id'); 
            // store the orig action 
            // to put back after submitting to server
			var orig_action  = $(this).attr('action');  
			var hiddenFrame = null;
			$(this).attr('id');
            var message_holder = settings.message_holder;
			var btn_submit = null;
            

            $("#load_form").hide();
            if( !settings.init_hide ){
                $(_form).show();
            }

            $('input[type=submit]',_form).click(function(){ 
                    
                    $(window).scrollTop(200);
                    btn_submit = this;
                    
                    var is_response = false;
                    //-------------------------------------
                    // lets handle validation and get error
                    // according to type of fields
                    var error = $(_form).validateform();
                    var bool_error = false;
                    var error_message = '';
                    if(error.required_error){  
                        error_message = 'Please check required fields.<br />';
                        bool_error = true;
                    }
                    if(error.email_error){ 
                        error_message += 'Invalid Email address.';
                        bool_error = true;
                    } 
                    if(bool_error){
                        found_error(error_message);
                        
                        return false;
                    }

                    //-----end of validation
                    // if we reach this place means no error    
                    toggle_submit_button()
                    
					if( settings.action!=null ){
						$(_form).attr('action',settings.action);
					}
                    
                    if(hiddenFrame==null){
                       // auto abort if server does not respond in 30 seconds
                       var t = setTimeout(function(){  
                            if(is_response)
                                return;
                            op_abort(); 
                            toggle_submit_button()
                            clearTimeout(t);
                            try{
                                document.execCommand('Stop');
                            }catch(e){}
                            try{
                                window.stop();
                            }catch(e){}
                       },30000); 
                       
                       $('#'+id).attr('target','hf_'+id); 
					   hiddenFrame = $('<div style="display:none" ><iframe id="hf_'+id+'" name="hf_'+id+'" src="about:blank"  ></iframe></div>').appendTo('body');	 
                        
                       $.pageLoading(1);
                       $("iframe",hiddenFrame).load(function(){ 
                                $.pageLoading(0);
                                clearTimeout(t);
                                is_response = true;
                                // put back orig action 
								if( settings.action!=null ){
									$(_form).attr('action',orig_action);
								} 
                                var json = null;
                                var content = null;
                                var content = $(this).contents();
                                var is_json = true;
                                
                                $(content).find('.html').each(function(){ 
                                    is_json = false;
                                });
                                if(is_json){ 
                                    eval('json='+ $(this).contents().text() ); 
                                }
                                
                                var  user_output=null; 
                                if(settings.done!=null){
                                   
                                    if(is_json){
                                         user_output = settings.done( json );  
                                    }else{
                                         user_output = settings.done( content );  
                                    }
                                    
                                    if( user_output != null  ){
                                        if( user_output[0] =='success' ){
                                            successfull(); 
                                        }else if( user_output[0] =='failed' ){
                                            found_error(user_output[1]); 
                                        }
                                    }
                                     
            					}
                                 
        					    if( user_output == null  ){
                                
    				                if(is_json){
                                        if(json.error=="true"){ 
                                            found_error(json.error_msg); 
                    					}else{
                    					   successfull();
                                           if(json.redirect!=null){
                    					       setTimeout(function(){  window.location.href = json.redirect; },1000);  
                                           }
                                        } 
                                     }else if(content){ 
                                        done(content)
                                     }
                                }
                                      
                                toggle_submit_button() 
    				   });
                    }    
                    settings.loading();
			}) 
            function toggle_submit_button(){
               
                if( settings.hidecontrol!=null){
                    //$(settings.hidecontrol).toggle();
                }else{
                    //$(btn_submit).toggle(); 
                }
                
                
            }            
            function found_error(msg){  
	 	         $("#"+message_holder).show_message({header:'<strong>Error found!</strong>',message:msg,duration:20000,type:'error'}); 	 
        	}  
        	function successfull(){
        		$("#"+message_holder).show_message({message:"Successfull...",duration:20000,type:'success'}); 	   
        	}
            function done(content){
                errors  = $(content).find('.errors'); 
                if( errors.hasClass('errors') ){  
                    found_error(errors.html()) 
                }else{
                    successfull();
                }
            }
            function loading(){
        		$("#"+message_holder).show_message({message:"Please wait...",duration:20000,type:'requesting'}); 
        	}
            function op_abort(){
                $("#"+message_holder).show_message({message:"Sorry, server is busy please try again",duration:20000,type:'error'}); 
            }
	}
    /*
    $.myFlash = function(options){
        
        var settings = {message:''};
        settings = $.extend({},settings,options); 
       
        var flashID = 'flash'+ parseInt(Math.random()*5000);
        
        flashDiv = $('<div id="'+ flashID +'" ></div>').appendTo('body'); 
        $(flashDiv).html(settings.message);
       // $(dialogDiv).css({position:'absolute',right:0,bottom:0});
        
    }
     */
    $.myDialog = function(options){
        
        
        var _parent = this;
        var settings = {url:null,vars:null}; 
        settings = $.extend({},settings,options);
        
        var dlgID = 'dlgID'+ parseInt(Math.random()*5000); 
        
        dialogDiv = $('<div id="'+ dlgID +'" ></div>').appendTo('body');
        
        var urlvars = 'dlgID='+ dlgID ;
         
        if( settings.vars == null ){
            urlvars = '?'+ urlvars; 
        }else{
            urlvars = '?'+ settings.vars+'&'+ urlvars;
        }
        $.pageLoading(1);
        $(dialogDiv).load(options.url+''+urlvars,function(){$.pageLoading(0)});

    }
    
    $.pageLoading = function(flag){ 
        if(flag==1){
            $("#bottomBar").show();
        }else{ 
            $("#bottomBar").hide();
        } 
    }
    
 
})(jQuery);

 
