///////////////////////////////////
function timedCount(){
var c;
c=c+1;
console.info('Ya Rab '+Math.random());
t=setTimeout("timedCount();",10000);
}
//timedCount();
/////////////////////////////////////
var sampleCallback = function(data,ioArgs,widgetRef){
			if(data){
				if(data.status && data.status == "success"){
				var file =  data.details;
				console.info("Input field Name : "+data.name+" File Uploaded : "+file.name+" File Size : "+file.size+" New file name : "+data.target);
					widgetRef.overlay.innerHTML = "Success File: "+file.name+"<input type='hidden' name='"+data.name+"' value='"+data.target+"' >" ;
				}else{
				console.warn("Status : "+data.status+" Field :"+data.name+" Error : "+data.error);
					widgetRef.overlay.innerHTML = "Error:"+data.error;
				}
			}else{
				// debug assist
				console.log('NO return :',arguments);
			}
		}
/////////////////////////////////////		
		var i = 0;
		function addNewUpload(divname,urlx){
			var node = document.createElement('input');
			dojo.byId(divname).appendChild(node);
			var widget = new dojox.form.FileInputAuto({
				id: divname+(++i),
				url: urlx,
				name: divname+i,
				triggerEvent : "onchange",
				onComplete: sampleCallback
			},node);
			widget.startup();
			return i;
		}
/////////////////////////////
function set_div_value(divname,value){
var contentNode = dojo.byId(divname);
var dodod =  function(){
contentNode.innerHTML = value;
};
dojo.addOnLoad(dodod);
}
/////////////////////////////////////
function showDialog(Dialog) {
	dijit.byId(Dialog).show();
}
/////////////////////////////////////
function hideDialog(Dialog) {
	dijit.byId(Dialog).hide();            
}
///////////////////////////////////// 
function create_chart(Seriesname,divname,seriesData,seriesDataLabels,color,marker,seriesvalue){
   dojo.require("dojox.charting.Chart2D");
     var chart1;
     if(!marker){
     marker = true;
     }
     if(!color){
     color = 'cyan';
     }
 dojo.addOnLoad(function(){
    chart1 = new dojox.charting.Chart2D(divname);
    chart1.addPlot("default", {
      type: "Lines", 
      markers: marker, 
      tension:3, 
      shadows: {dx: 2, dy: 2, dw: 2}
    });
    chart1.addAxis("x", {fixLower: "major", fixUpper: "major", labels: seriesDataLabels});
    chart1.addAxis("y", {vertical: true, fixLower: "major", fixUpper: "major", natural: true});
    chart1.addSeries(Seriesname, seriesData);
    if(seriesvalue){
    chart1.updateSeries(Seriesname, seriesvalue);
    }
    // Load the required color plot information
    dojo.require("dojox.charting.themes.PlotKit." + color);
    chart1.setTheme(dojox.charting.themes.PlotKit[color]);
    chart1.render();
  });
  }
  /////////////////////////////////////
  function chart_chnage_value(Seriesname,seriesvalue){
       var updateFn = function(){
        seriesData[index] = seriesC[index];
        chart1.updateSeries(Seriesname, seriesData);
        chart1.render();
      };
      // Update the change when the values are changed.
     // dojo.connect(input, "setValue", updateFn);
  }
    
	function checkforvalue(field,value,divname,sign){
	if(sign == 'show'){
		if(field == value){
			state = 'visible';
		}else{
      		state = 'hidden';
      	}
    }else if(sign == 'hide'){
    	if(field == value){
			state = 'hidden';
		}else{
      		state = 'visible';
      	}
    }
		if (document.all) { //IS IE 4 or 5 (or 6 beta)
			eval( "document.all." + divname + ".style.visibility = state");
		}
		if (document.layers) { //IS NETSCAPE 4 or below
			document.layers[divname].visibility = state;
		}
		if (document.getElementById && !document.all) {
			divaya = document.getElementById(divname);
			divaya.style.visibility = state;
		}
	}


/////////////////////////////////////
function upload_file_ajax(urlx,formname,file_field,progras_continer,field_container,divresult,fieldresult,type){
  if(type == ''){
  type == 'multi'
  }
  //Hide the file input field
  dojo.style(field_container,"display","none");

  //Show the progress bar
  dojo.style(progras_continer,"display","inline"); 
  dojo.byId(field_container).innerHTML = "Uploading ..."; 
//submiting the ajax files
  dojo.io.iframe.send({
    url: urlx,
    method: "post",
    handleAs: "text",
    form: dojo.byId(formname),
    handle: function(data,ioArgs){
      var foo = dojo.fromJson(data);
      if (foo.status == "success"){
      
      	if(type == "multi"){
        //Show the file input field contanier and reset input field value
        dojo.style(dojo.byId(field_container),"display","inline");
        dojo.byId(file_field).value = '';
        
        //Hide the progress bar and show result
        dojo.style(dojo.byId(progras_continer),"display","none"); 
        dojo.byId(divresult).innerHTML += "success: File: " + foo.details.name 
          + " size: " + foo.details.size +"<input type='hidden' name='"+fieldresult+"[]' value='"+foo.details.name+"'> <br>"; 
        //dojo.byId('preamble').innerHTML = "File to Upload: ";  
		}else{
		 //Show the file input field contanier and reset input field value
        dojo.style(dojo.byId(field_container),"display","none");
        dojo.byId(file_field).value = '';
        //Hide the progress bar and show result
        dojo.style(dojo.byId(progras_continer),"display","none");
        dojo.byId(divresult).innerHTML = "success: File: " + foo.details.name 
          + " size: " + foo.details.size +"<input type='hidden' name='"+fieldresult+"' value='"+foo.details.name+"'> <br>";
       // dojo.byId('preamble').innerHTML = "File to Upload: ";
		}   
		 
      }else{
        dojo.style(dojo.byId(field_container),"display","inline");
        dojo.style(dojo.byId(progras_continer),"display","none"); 
        dojo.byId(divresult).innerHTML = "Error, Time Out try again ";
      }  
    }
  });
}







/////////////////////////////////////
function new_dojo_tab(Tabcountiner,Name,Link) {
var init = function(){
		// create a ContentPane
		var newChild = new dijit.layout.ContentPane({
                                                href: Link,
                                                title: Name,
                                                refreshOnShow:true,
                                                preventCache:true
                                               	
                                        }, 
                                        dojo.doc.createElement("div")
                                );
                        
		// find my tabContainer and add our new ContentPane
		dijit.byId(Tabcountiner).addChild(newChild);
		console.log('Adding new tab : '+newChild.id);
		//newChild.loadingMessage = 'Loaded' + console.log('Loading');
		newChild.onLoad(console.log('Loading'+newChild.id));
		// find parent Container and subscribe to selectChild event
		// without it refreshOnShow and href load wont work.
        newChild.startup();          
             }
dojo.addOnLoad(init);
}

/////////////////////////////////////
function ajax_url(parm,divname,go){
	var contentNode = dojo.byId(divname);
		dojo.query('[widgetId]', contentNode).forEach( function(node) {
			var widget = dijit.byNode(node);
			if (widget)
				widget.destroy();
		});
	var init = function(){
	if(parm){t = "&"+parm+"&sid="+Math.random();}else{t = "&sid="+Math.random();}
	var urlx = go+t;
	//var LoadingMsg = "<img src='" + IMGPATH + "includes/images/loading_animation.gif' align='center'>";
	var LoadingMsg = "";
	dojo.require("dojo.parser");
		dojo.xhrGet( {
			url :urlx,
			load : function(data, args) {
				// fade out the node we're modifying
			dojo.fadeOut( {
				node :contentNode,
				duration :100,
				beforeBegin : function() {
					// set the data, fade it back in
				contentNode.innerHTML = LoadingMsg;
				console.log("Posting data & parsing Content");
				dojo.eval(dojo.parser.parse(contentNode));
				// dojo.fadeIn({node: contentNode,duration: 1000,
				// delay:5}).play();
			},
			onEnd : function() {
				// set the data, fade it back in
				contentNode.innerHTML = data;
				dojo.eval(dojo.parser.parse(contentNode));
				console.log('Get requested url : ' + urlx + '');
				dojo.fadeIn( {
					node :contentNode,
					duration :100,
					delay :0
				}).play();
			}
			}).play();
		},
		// if any error occurs, it goes here:
			error : function(error, args) {
				console.warn("error!", error);
			}
		});
	};
	dojo.addOnLoad(init);
}
/////////////////////////////////////
function hide_div(divName){
		document.getElementById(divName).style.visibility = "hidden";
		document.getElementById(divName).style.display = "none";
}
/////////////////////////////////////
function show_div(divName){
	document.getElementById(divName).style.visibility = "visible";
	document.getElementById(divName).style.display = "inline";
}
/////////////////////////////////////
function ajax_form_submit(link,divname,formname) {
  //The form data is sent to the given URL using a POST method, 
  //rather than a GET by using the dojo.xhrPost function.

dojo.require("dojo.parser");
dojo.require("dojo.io.iframe");
var contentNode = dojo.byId(divname);
  dojo.xhrPost({
    url: link,
    load: function(response, ioArgs){
      contentNode.innerHTML = response;
      dojo.parser.parse(contentNode);
      //Dojo recommends that you always return(response); to propagate 
      //the response to other callback handlers. Otherwise, the error 
      //callbacks may be called in the success case.
      return response;
    },
    error: function(response, ioArgs){
      contentNode.innerHTML = 
        "An error occurred, with response: " + response;
           dojo.parser.parse(contentNode);   
      return response;
    },
    
    //Setting the 'form' parameter to the ID of a form on the page
    //submits that form to the specified URL
    form: formname
  });
    dojo.query('[widgetId]', dojo.byId(divname)).forEach(function(node){
var widget = dijit.byNode(node);
if(widget)
widget.destroy();
})
}
/////////////////////////////////////
var c=0;
function ajax_timer(divname,goz,secound){
	
if(secound){
secound = secound * 1000;
}else{
secound = 5000;
}
c= c+1;
var t;
//var a = alert("hiii");
var x = ajax_timer(divname,goz,secound);
t = self.setTimeout(x,5000);
return c;
}
/////////////////////////////////////
//begin of tiny mce editor 
function ajax_editor_Load(fieldid,data) {
//alert('Loading');
var ed = tinyMCE.get(fieldid);
// Do you ajax call here, window.setTimeout fakes ajax call
ed.setProgressState(1); // Show progress
window.setTimeout(function() {
ed.setProgressState(0); // Hide progress
//ed.setContent(data);
if(ed.setContent(data)){
alert('loadded');
}
}, 3000);
}
/////////////////////////////////////
function ajax_editor_Save(editorid,url,div,form) {
var ed = tinyMCE.get(editorid);
ed.setProgressState(1); // Show progress
window.setTimeout(function() {
ed.setProgressState(0); // Hide progress
var valueStore  = ed.getContent();
if(valueStore){
tinyMCE.execCommand('mceFocus', false, editorid);                    
tinyMCE.execCommand('mceRemoveControl', false, editorid);
dojo.byId(editorid).value = valueStore;
ajax_form_submit(url,div,form);
}
}, 3000);
}
function new_editor(editorid){
tinyMCE.init({
mode : "exact",
elements : editorid,
theme : "advanced",
skin : "o2k7",
relative_urls : true,
plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
theme_advanced_buttons1 : "newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left",
theme_advanced_statusbar_location : "bottom",
theme_advanced_resizing : true,
//remove_script_host : true,
//cleanup_on_startup : true,
//cleanup: true,
save_callback: "ajax_editor_Save",
file_browser_callback : "ajaxfilemanager",
spellchecker_languages : "+English=en,Arabic=ar,French=fr,Italian=it,German=de,Spanish=es,Greek=el,Dutch=nl,Swedish=sv",
// Example content CSS (should be your site CSS) 
content_css : "css/example.css",
// Drop lists for link/image/media/template dialogs 
template_external_list_url : "js/template_list.js",
external_link_list_url : "js/link_list.js",
external_image_list_url : "js/image_list.js",
media_external_list_url : "js/media_list.js",

// Replace values for the template plugin 
template_replace_values : { 
username : "<?=rand ( 5, 100 )?>", 
password : "<?=rand ( 5, 100 )?>"
}
});
}
//////////////////////////////////////////////////////////////////
function ajaxfilemanager(field_name, url, type, win) {
			var ajaxfilemanagerurl = "../ajaxfilemanager/ajaxfilemanager.php";
			switch (type) {
				case "image":
					break;
				case "media":
					break;
				case "flash": 
					break;
				case "file":
					break;
				default:
					return false;
			}
            tinyMCE.activeEditor.windowManager.open({
                url: "../ajaxfilemanager/ajaxfilemanager.php",
                width: 782,
                height: 440,
                inline : "yes",
                close_previous : "no"
            },{
                window : win,
                input : field_name
            });
            
            return false;			
			var fileBrowserWindow = new Array();
			fileBrowserWindow["file"] = ajaxfilemanagerurl;
			fileBrowserWindow["title"] = "File Manager";
			fileBrowserWindow["width"] = "782";
			fileBrowserWindow["height"] = "440";
			fileBrowserWindow["close_previous"] = "no";
			tinyMCE.openWindow(fileBrowserWindow, {
			  window : win,
			  input : field_name,
			  resizable : "yes",
			  inline : "yes",
			  editor_id : tinyMCE.getWindowArg("editor_id")
			});
			
			return false;
		}
//////////////////////////////////////////