//Created by Harry Bomrah on Sep 21 2011
$rss = jQuery.noConflict();
var rcom={
//Pass dom and will return binded dom with starting year till current
insertDatePanel : function(dom,year){
	if(!year)year=1901;
	if(dom=="")return false;
	domid=dom.attr("id");
	var dt = new Date();
	current_year=dt.getFullYear();
	var dthtml="Year: <select name='"+domid+"_year'>";
	for(i=current_year;i>=year;i--){
		dthtml+="<option value='"+i+"'>"+i+"</option>";
	}
	dthtml+="</select> Date: <select name='"+domid+"_date'>";
	for(i=1;i<=31;i++){
		if(i<10)
			dthtml+="<option value='0"+i+"'>"+i+"</option>";
		else
			dthtml+="<option value='"+i+"'>"+i+"</option>";
	}
	dthtml+="</select> Month: <select name='"+domid+"_month'>";
	var months= Array("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
	for(i=1;i<12;i++){
		if(i<10)
			dthtml+="<option value='0"+i+"'>"+months[i]+"</option>";
		else
			dthtml+="<option value='"+i+"'>"+months[i]+"</option>";
	}
	dthtml+="</select>"; 
	dom.html(dthtml);
},

//loading overlay around a dom...
loadingWrapper : function(dom, display){
	if(display){
		dom.prepend("<div id='loading_wrapper' class='loading'></div>");
		$rss("#loading_wrapper").height(dom.height());
		$rss("#loading_wrapper").width(dom.width());
	}else{
		domId=dom.attr("id");
		$rss("#"+domId+" #loading_wrapper").remove();
		}
	},
	
//validating a dom.... 
validate : function(dom, validation, errormsg){
	var domValue = dom.val();
	var error = false;
	var regex="";
	var msg = "";
	switch(validation){
		case "required":
			if(domValue=="")error=true;
			msg="Cannot be empty.";
			break;
		case "email":
			regex=/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
			msg="Invalid Email Address.";
			break;
		case "number":
			regex=/^\d*[0-9](|.\d*[0-9]|,\d*[0-9])?$/;
			msg = "Only numbers are accepted.";
			break;
		case "alphanumeric":
			regex=/^\s*[a-zA-Z0-9,\s]+\s*$/;
			msg="Only numbers, alphabets and spaces are allowed.";
			break;
		}
		domId=dom.attr("name");
		if(errormsg=="")errormsg=msg;
		if(regex!="")if(!regex.test(domValue))error=true;
		if(error){$rss("#"+domId+"_error").remove();dom.after("<span id='"+domId+"_error' class='error'>"+errormsg+"</span>");return false;} else{ $rss("#"+domId+"_error").remove();return true;}
	},
	
bindToSpinner : function(dom,data,callbackFn){
		var domId = dom.attr("id");
		var dhtml="";
		var spinnerValue=Array();
		var spinnerDisplay=Array();
		$rss.each(data,function(i,it){
			$rss.each(data[i],function(key,it){
				spinnerValue.push(it);
			});
		});
		dhtml="<select name='"+domId+"'>";
		for(i=0,y=1,z=0;i<spinnerValue.length/2;i++,y+=2,z+=2){
			dhtml+="<option value='"+spinnerValue[z]+"'>"+spinnerValue[y]+"</option>";
		}
		dhtml+="</select>";
		dom.html(dhtml);
		if(typeof callbackFn=="function")
			callbackFn.call(this, dhtml);
	},
	
	//binds the recieved json to a table
bindToTable : function(dom,data,headers,actions,css_class,callbackFn){
	if(!css_class)css_class="";
	var dhtml="<table width='100%' cellpadding='5' cellspacing='5' class='"+css_class+"' ><thead><tr>";
	var domId = dom.attr("id");
	if(actions){
		var btnTitles=Array();
		var btnFunctions=Array();
		$rss.each(actions,function(title,func){
			btnTitles.push(title);
			btnFunctions.push(func);
		});
		rcom.translate(btnTitles,function(convertedData){
				btnTitles=convertedData.slice();
		
			rcom.translate(headers,function(convertedData){
				headers=convertedData;
				if(!data)return;
				$rss.each(headers,function(i,head){
					dhtml+="<th>"+head+"</th>";
				});
				dhtml+="</thead></tr>";
				if(data.length==0)dhtml+="<tr><td colspan='"+headers.length+"' align='center'>No Data</td></tr>";
				$rss.each(data,function(i,item){
					var cl="";
					if(i%2!=0)cl="even";
					dhtml+="<tr id='"+domId+"_"+item.id+"' class='"+cl+"'>";
					$rss.each(item,function(i,it){
						if(i!="id"){
							if(it==null)it="Not Set";
								dhtml+="<td align='center'>"+it+"</td>";
						}
					})
					dhtml+="<td align='center'>";
					for(x=0;x<btnTitles.length;x++){
						dhtml+="<button onclick='"+btnFunctions[x]+"("+item.id+")'>"+btnTitles[x]+"</button>";
					}
					dhtml+="</td>";
					dhtml+="</tr>";
				});
				dhtml+="</table>";
				dom.html(dhtml);
				});
		});
	}else{
			rcom.translate(headers,function(convertedData){
				headers=convertedData;
				if(!data)return;
				if(headers.length>0){
					$rss.each(headers,function(i,head){
						dhtml+="<th>"+head+"</th>";
					});
				}
				dhtml+="</thead></tr>";
				if(data.length==0)dhtml+="<tr><td colspan='"+headers.length+"' align='center'>No Data</td></tr>";
				
				$rss.each(data,function(i,item){
					var cl="";
					if(i%2!=0)cl="even";
					dhtml+="<tr id='"+domId+"_"+item.id+"' class='"+cl+"'>";
					$rss.each(item,function(i,it){
						if(i!="id"){
							if(it==null)it="Not Set";
								dhtml+="<td align='center'>"+it+"</td>";
						}
					})
					dhtml+="</tr>";
				});
				dhtml+="</table>";
				dom.html(dhtml);
				});	
	}
	
	if(typeof callbackFn=="function")
		callbackFn.call(this, dhtml);
},
	//convert to date string which can be directly inserted in database or according to any format.
convertToInsertableDate : function(y,m,d,format){
		var dt="";
		if(m<10)m="0"+m;
		if(d<10)d="0"+d;
		switch(format){
			case "yyyy-mm-dd":
				dt= y+"-"+m+"-"+d;
			break;
			case "dd-mm-yyyy":
				dt= d+"-"+m+"-"+y;
			break;
			case "mm-dd-yyyy":
				dt= m+"-"+d+"-"+y;
			break;
			default:
				dt= y+"-"+m+"-"+d;
			break;
		}
		return dt; 
	},
//a fucntion to show specific divs and hide all other	
showDoms : function(doms){
	$rss("body").find("div").each(function(){$rss(this).hide();});
	$rss.each(doms,function(i,dom){
			dom.show();
		});
	},

//a function to translate the word or array..
translate : function(data,callbackFn){
		var cdata="";
		var status =true;
		if(!data){
			if(typeof callbackFn=="function")
						callbackFn.call(this,cdata);
				status=false;
			}
		if(data==""){
			if(typeof callbackFn=="function")
						callbackFn.call(this,cdata);
				status=false;
			}
		if(status){
			$rss.getJSON("../../classes/translate.php", {fn:"translateThis",tData:data},function(convertedData){			
				if(typeof callbackFn=="function")
						callbackFn.call(this, convertedData);
			});
		}
	},

// a function to bind JSON to list
bindToList : function(dom,data,callbackFn){
		var domId = dom.attr("id");
		var dhtml="";
		var listValue=Array();
		var listDisplay=Array();
		$rss.each(data,function(i,it){
			$rss.each(data[i],function(key,it){
				listValue.push(it);
			});
		});
		dhtml="<ul id='"+domId+"_list'>";
		for(i=0,y=1,z=0;i<listValue.length/2;i++,y+=2,z+=2){
			dhtml+="<li id='li_"+listValue[z]+"'>"+listValue[y]+"</li>";
		}
		dhtml+="</ul>";
		dom.html(dhtml);
		if(typeof callbackFn=="function")
			callbackFn.call(this,dhtml);
	},
makeDraggable : function(handler,dom){
	handler.css("position","absolute");
	dom.css("position","absolute");
	var puranix=0;
	var nayeex=0;
	var puraniy=0;
	var nayeey=0;
	var offset="";
	var zIndex=dom.css("z-index");
		handler.mousedown(function(e){
			puranix=e.clientX;
			puraniy=e.clientY;
			offset=dom.offset();
			$rss(this).mousemove(function(e){
				nayeex=e.clientX-puranix;
				nayeex+=offset.left;
				nayeey=e.clientY-puraniy;
				nayeey+=offset.top;
				dom.css({"left":nayeex+"px","top":nayeey+"px","z-index":"9999"});
			})
		}).mouseup(function(){
			$rss(this).unbind("mousemove");
			dom.css("z-index",zIndex);
		})
	},
	
//automatically scrolls to the bottom of the div	
scrollToBottom : function(dom){
	var domId = dom.attr("id");
//	var domScrollHeight = document.getElementById(domId).scrollHeight; 
	var obj = document.getElementById(domId);
	
	if((obj.scrollTop+100) >= (obj.scrollHeight - obj.offsetHeight))
		dom.scrollTop(obj.scrollHeight);
	},
	
/*ajax loading of images... needs following settings
dom:in which images ve to be loaded
url:the server url for making ajax calls
limit:how many images to load
divClass:the class of div surrounding each image
nameClass:class for span showing name
fn:function to be called in on the server
imageSrc:the image source of all the images.
bindTo:to bind images to a onclick function or else will be binded to normal a tag.
urlKey:to specify the key of the value.. if bindTo is used, this will be neglected..
returns json;
*/
loadImages : function(settings,callbackFn){

		var dom = settings.dom;
		var domid= dom.attr("id");
		var temp_array=Array();
		var starting = $rss("#"+domid+" img:last").attr("id");
		if(typeof starting != 'undefined'){
			starting = starting.substr(4,starting.length-1);	
		}else{starting = 0};
		var temp_var="";
		var json = "";
		var dhtml="";
		var extraparam="";
		if(typeof settings.extraParam != "undefined"){
			extraparam = settings.extraParam;
		}
		$rss.getJSON(settings.url,{fn:settings.fn,id:settings.whereId,limit:settings.limit,start:starting,extra:extraparam},function(images){
				json = eval(images);
				$rss.each(images,function(i,pic){
					var temp_array=Array();
					var a_var=Array();
					var name_var="";
					var title="";
					$rss.each(pic,function(i,value){
						temp_array.push(value);
						})
						if(temp_array.length>=4){
							name_var="<span class='"+settings.nameClass+"'>"+temp_array[3]+"</span></div>" 	
						}
						if(temp_array[2]==null)
							title = "";
						else
							title = temp_array[2];
						if(typeof settings.bindTo!="undefined"){
							a_var[1]="onclick='"+settings.bindTo+"("+temp_array[0]+");return false;'";
							a_var[0]="";
						}else{a_var[0]='?'+settings.urlKey+'='+temp_array[0];a_var[1]="";}
					dhtml="<div class='"+settings.divClass+"' id='img_holder_"+temp_array[0]+"' ><a href='"+a_var[0]+"' "+a_var[1]+" title='"+title+"'><img  id='pic_"+temp_array[0]+"' style='display:none' src='"+settings.imageSrc+temp_array[1]+"' /></a>"+name_var;
				dom.delay(100).append(dhtml);	
				$rss("#pic_"+pic.id).delay(100).fadeIn(200);
				
				})
				if(typeof callbackFn=="function")
					callbackFn.call(this,json);
		})
		
		
	},
	
//function to get url variables...
getUrlVars : function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++){
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    if(vars[0] == window.location.href){
    	vars =[];
    }
    return vars;
},
/*function to open a modalwindow on a page.. self reliant no images, no css needed.
settings

width:in percentage or pixcel
height:in percentage or pixcel
closeBtn:true or false
envClose:closing through background click, true or flase
loadDiv:load html from a div
loadPage:load a page
loadHtml: load html

*/
modalWindow : function(settings,callbackFn){
	
	var envClose = settings.envClose;
	var dhtml="";
	if(typeof envClose == "undefined")
		envClose = true;
	var closeBtn = settings.closeBtn;
	if(typeof closeBtn == "undefined")
		closeBtn = true;

	var rgmaskHeight = $rss(window).height();
	var rgmaskWidth = $rss(window).width();
	var tempheight = settings.height;
	var tempwidth = settings.width;
		
	var maxheight = (rgmaskHeight*85)/100;
	var maxwidth = (rgmaskWidth*85)/100;
		
	if(typeof tempheight!="undefined"){
		tempheight = tempheight.toString();
		if(tempheight.charAt(tempheight.length-1)=='%')
			tempheight=(rgmaskHeight*parseInt(tempheight.substr(0,tempheight.length)))/100;
		if(tempheight>maxheight)
			tempheight=maxheight;	
	}else{tempheight="auto";}
	if(typeof tempwidth!="undefined"){
		tempwidth = tempwidth.toString();
		if(tempwidth.charAt(tempwidth.length-1)=='%')
			tempwidth=(rgmaskWidth*parseInt(tempwidth.substr(0,tempwidth.length)))/100;
		if(tempwidth>maxwidth)
			tempwidth=maxwidth;
	}else{tempwidth="auto";}
	$rss("body").append('<div class="rgmask" id="rgsheath" style="height:'+rgmaskHeight+'px"></div>');
	$rss("#rgsheath").css({background: "#000", width: "100%", position: "fixed", top: 0, left: 0,opacity:0.5,'z-index':199});
	$rss("body").append('<div id="rgWindow"></div>');
	$rss("#rgWindow").css({"position": "fixed", "z-index": "999", "background": "#fff", "border": "solid 1px #ccc", "padding": "10px", "border-radius": "5px", "-webkit-border-radius": "5px", "-moz-border-radius": "5px", "-ms-border-radius": "5px",	"box-shadow": "0 0 20px rgba(0,0,0,0.7)","-webkit-box-shadow": "0 0 20px rgba(0,0,0,0.7)","-moz-box-shadow": "0 0 20px rgba(0,0,0,0.7)","-ms-box-shadow": "0 0 20px rgba(0,0,0,0.7)"});
		var rgWTop = (rgmaskHeight-20)/2;
		var rgWLeft = (rgmaskWidth-20)/2;
		$rss("#rgWindow").css({top:rgWTop+"px", left:rgWLeft+"px"});
	if(typeof settings.loadDiv!="undefined"){
		dhtml = $rss(settings.loadDiv).html();
		$rss("#rgWindow").html(dhtml).hide();
		prepareWindow();
	}
	if(typeof settings.loadHtml!="undefined"){
		dhtml = settings.loadHtml;
		$rss("#rgWindow").html(dhtml).hide();
		prepareWindow();
	}
	if(typeof settings.loadPage!="undefined"){
		$rss("#rgWindow").load(settings.loadPage,function(){$rss(this).hide();dhtml=$rss(this).html();prepareWindow();});
	}
	function prepareWindow(){
		if(tempheight!="auto")
			rgWTop = (rgmaskHeight-tempheight)/2;
		else{
			tempheight=$rss("#rgWindow").height()+30;
			if(tempheight>maxheight)
				tempheight=maxheight;
			rgWTop=(rgmaskHeight-tempheight)/2;
		}
		if(tempwidth!="auto")
			rgWLeft = (rgmaskWidth-tempwidth)/2;
		else{
			tempwidth=$rss("#rgWindow").width();
			if(tempwidth>maxwidth)
				tempwidth=maxwidth;
			rgWLeft=(rgmaskWidth-tempwidth)/2;
		}
		tempwidth=parseInt(tempwidth)+25;
		$rss("#rgWindow").empty().show();
		var closebtn = "";
		if(closeBtn)
			closebtn='<a href="" style="display:block; width:20px; height:20px; line-height:19px; text-align:center; position:absolute; right:-10px; top: -10px; font-family:Tahoma; font-weight:bold; border:solid 1px #000; border-radius: 10px;text-shadow:0px 1px 0 #DDD; background-color:#CCC; font-size:10px; text-decoration:none; color:#666; padding-left:1px; box-shadow: 0 0 5px #000000;" id="close_modal">X</a>';
		$rss("#rgWindow").animate({"width":tempwidth+"px","height":tempheight+"px",top:rgWTop+"px", left:rgWLeft+"px"},500,function(){$rss("#rgWindow").html(closebtn+"<div id='rgContent' style='padding:5px; overflow:auto; overflow-x:none; height:"+tempheight+"px;'>"+dhtml+"</div>");
		$rss("#close_modal").mouseover(function(){$rss(this).css("color","#999");}).mouseout(function(){$rss(this).css("color","#666");})
		$rss("#close_modal").click(function(){rcom.modalWindowClose(); return false;})
			if(envClose)
				$rss("#rgsheath").click(function(){
					rcom.modalWindowClose();
				})
				$rss(document).one("keydown",function(e){
				    if (e.keyCode == 27){ 
				    	rcom.modalWindowClose();
				       return false;
				    }
			})

			if(typeof callbackFn=="function")
				callbackFn.call(this,$rss("#rgWindow"));
		});
	}
},
modalWindowUpdate : function(settings,callbackFn){
	var rgmaskHeight = $rss(window).height();
	var rgmaskWidth = $rss(window).width();
	var tempheight = settings.height;
	var tempwidth = settings.width;
	var dhtml = "";
	var maxheight = (rgmaskHeight*85)/100;
	var maxwidth = (rgmaskWidth*85)/100;
	if(typeof tempheight!="undefined"){
		tempheight = tempheight.toString();
		if(tempheight.charAt(tempheight.length-1)=='%')
			tempheight=(rgmaskHeight*parseInt(tempheight.substr(0,tempheight.length)))/100;
		if(tempheight>maxheight)
			tempheight=maxheight;	
	}else{tempheight="auto";}
	if(typeof tempwidth!="undefined"){
		tempwidth = tempwidth.toString();
		if(tempwidth.charAt(tempwidth.length-1)=='%')
			tempwidth=(rgmaskWidth*parseInt(tempwidth.substr(0,tempwidth.length)))/100;
		if(tempwidth>maxwidth)
			tempwidth=maxwidth;
	}else{tempwidth="auto";};
	$rss("body").append("<div id='rgwindow_temp_div'></div>");
	
	if(typeof settings.loadDiv!="undefined"){
		dhtml = $rss("#"+settings.loadDiv).html();
		$rss("#rgwindow_temp_div").html(dhtml).hide();
		prepareWindow();
	}
	if(typeof settings.loadHtml!="undefined"){
		dhtml = settings.loadHtml;
		$rss("#rgwindow_temp_div").html(dhtml).hide();
		prepareWindow();
	}
	if(typeof settings.loadPage!="undefined"){
		$rss("#rgwindow_temp_div").load(settings.loadPage,function(){$rss(this).hide();dhtml=$rss(this).html();prepareWindow();});
	}
	function prepareWindow(){
		if(tempheight!="auto")
			rgWTop = (rgmaskHeight-tempheight)/2;
		else{
			tempheight=$rss("#rgwindow_temp_div").height()+30;
			if(tempheight>maxheight)
				tempheight=maxheight;
			rgWTop=(rgmaskHeight-tempheight)/2;
		}
		if(tempwidth!="auto")
			rgWLeft = (rgmaskWidth-tempwidth)/2;
		else{
			tempwidth=$rss("#rgwindow_temp_div").width();
			if(tempwidth>maxwidth)
				tempwidth=maxwidth;
			rgWLeft=(rgmaskWidth-tempwidth)/2;
		}
		tempwidth=parseInt(tempwidth)+25;
			$rss("#rgContent").empty();
		$rss("#rgWindow").animate({"width":tempwidth+"px","height":tempheight+"px",top:rgWTop+"px", left:rgWLeft+"px"},500,function(){$rss("#rgContent").css("height",tempheight+"px").html(dhtml)});
		$rss("#rgwindow_temp_div").remove();
		}
},
modalWindowClose : function(callbackFn){
	if($rss("#rgWindow").length>0){
		$rss("#rgWindow").empty();
		var rgmaskHeight = $rss(window).height();
		var rgmaskWidth = $rss(window).width();
		var x = (rgmaskHeight-20)/2;
		var y = (rgmaskWidth-20)/2
		$rss("#rgWindow").animate({top:x+"px", left:y+"px","width":"50px","height":"50px"},300,function(){$rss(this).fadeOut(100).remove();$rss("#rgsheath").fadeOut(500).remove();})
	}
		if(typeof callbackFn=="function")
				callbackFn.call(this,"harry");
},
bindDomToHead :  function(dom){
	var gc = dom.css("background");
	var t = dom.offset();
	var gw = dom.width();
	$rss(window).scroll(function(){
		var wt = $rss(window).scrollTop();
		if ( wt > t.top ) {
			var cssObj = { 
				'position':'fixed',
				'top':0,
				'width':gw,
				'background':gc,
				'box-shadow':'0 1px 0 rgba(0,0,0,0.2)',
				'z-index':99
				}
			dom.css(cssObj);
		} else {
			dom.attr('style',"");
		}
	});
},
progressBar : function(dom,settings){
	var domid = dom.prop("id");
	if($rss("#rss_progressbar_div_"+domid).length==0){
		if(typeof settings.top == "undefined")
			settings.value = 1;
		if(typeof settings.top == "undefined")
			settings.top = (dom.height()-12)/2;
		dom.append("<div id='rss_progressbar_div_"+domid+"' style='display:none;padding: 2px;background: #333;background: -webkit-linear-gradient(#111, #333);background: -moz-linear-gradient(#111, #333);background: -ms-linear-gradient(#111, #333);position: absolute;top: "+settings.top+"px;left: 50%;margin-left: -45%;width: 84%;box-shadow: inset 0 0 2px #000;border-radius: 4px;'><div id='rss_progressbar_"+domid+"' style='height: 8px;	background: #36c;background: -webkit-linear-gradient(#7A98E7, #36c);background: -moz-linear-gradient(#7A98E7, #36c);background: -ms-linear-gradient(#7A98E7, #36c);border-radius: 2px; width: "+settings.value+"%;'></div></div>");
		$rss("#rss_progressbar_div_"+domid).fadeIn(500);
	}
},
progressBarValue : function(dom,value){
	var domid = dom.prop("id");
	if($rss("#rss_progressbar_div_"+domid).length==1){
		$rss("#rss_progressbar_"+domid).animate({"width":value+"%"},100);
		
	}
},
progressBarClose : function(dom){
	var domid = dom.prop("id");
	$rss("#rss_progressbar_div_"+domid).fadeOut(500,function(){$(this).remove();});
},
getInternetExplorerVersion: function(){
   var rv = -1; // Return value assumes failure.
   if (navigator.appName == 'Microsoft Internet Explorer')
   {
      var ua = navigator.userAgent;
      var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
      if (re.exec(ua) != null)
         rv = parseFloat( RegExp.$1 );
   }
   return rv;
   }
}
$ = jQuery.noConflict();