var lyn=0
var sfrag

$(document).ready(function(){


	$('#searchbutton').click(function(){ fetcharchives_byfilter('searchbox',$('#searchphrase').val(),'') })
			.addClass('clickable')

	// see if search was POSTed, php wrapper would have entered value into search box
	var sphrase=$('#searchphrase').val()
	if ((sphrase != 'Enter search phrase') && (sphrase != 'Enter Search Phrase'))fetcharchives_byfilter('searchbox',$('#searchphrase').val(),'')

	else  {  // sort through GET parameters
		$('#searchphrase').one("click", function() {  $(this).val('') })


		//retrieve whatever a containing (wrapper) php script might have put into the html
		var get_artpic=$("#logo").attr('artpic')
		var get_artno=$("#logo").attr('artno')

		var get_articlescat=$("#logo").attr('articlescat')
		var get_reviewscat=$("#logo").attr('reviewscat')
		var get_reviewpic=$("#logo").attr('getrvwpic')
		var get_rvwno=$("#logo").attr('rvwno')

		var get_wevt         = gup('wevt') //=$("#logo").attr('wevt')
		var get_wevt_in_logo = $("#logo").attr('wevt')  // only needed if it says "noajax" => SEO friendly serverside content, init some stuff now, like banners

//		var do_login=$("#logo").attr('login')
		var do_login = gup('login')
		var get_arch=$("#logo").attr('arch')  // dont use GET to fire fetching of archives, it might have been replaced by SEO getarchcore.php

		var get_passkey=$("#logo").attr('passkey')



		if (get_artpic!=undefined) {  //specific article requested by pic name, eg clicked on in homepage menu
						  // or redirected from uploads
			if (get_artpic=='#') fetcharticles('art')
			else fetcharticleforpic(get_artpic)
		}

		else if (get_artno!=undefined) {  //specific article requested by art no
						  // or redirected from uploads
			if (get_artno=='#') fetcharticles("art")
			else fetcharticlefor(get_artno)

		}

		else if (get_articlescat!=undefined) {  // mostly when main menu for this category was clicked
			if (get_articlescat=='dont') {
					logthis('no ajax')  // jquery_globals, refers to var logging
				if (canlogbannerevent>0) DoenAjax_logbannerevent('page','home','home')
				else	window.setTimeout( "waitforbanner()", 2000 );

			}
			else fetcharticles(get_articlescat)
		}
									// =========  reviews autoload

		else if (get_reviewscat!=undefined) {  // mostly when main menu for this category was clicked
//			fetchreviews(get_reviewscat);
			DoenAjax_fetchrvwtype (get_reviewscat)
		}

		else if (get_rvwno!=undefined) {
			DoenAjax_fetchrvwdetail_indiv(get_rvwno,"centreblock")
			// TODO: ensure this is placed in right spot, centreblock is ok for editing
		}

		else if (get_reviewpic!=undefined) {  // individual review was clicked
			DoenAjax_fetchrvwforpic(get_reviewpic)
		}

		else if ( (get_wevt != undefined) && (get_wevt != '') ) {
			// all events requested, second condition tests for empty but defined, as gup returns
			//alert('get_wevt='+get_wevt)
			if (get_wevt_in_logo == 'noajax') {
				setupevtanchors() // except navanchors ?? could be set otherwise it will be sent serverside for human clicks too
				DoenAjax_logbannerevent('page','evt','art-82')
			}
			else  fetchevents_byfilter(gup('filter'),gup('val'),gup('step'))   // code in jquery_evt.js
		}

		else if (get_arch!=undefined) {  // all events requested
			fetcharchives_byfilter('all','all','')
		}

		else if (do_login=='yes') {
			//alert(do_login)
			DoenAjaxBuildLoginbox('expanded')
		}
		else if (get_passkey != undefined) {
//			DoenAjaxBuildLoginbox('expanded')  // do nothing, allow php inserted message to stay
		}

		else { fetcharticles("art") }
	} // end of get parameters

	 $("#logo")
		 .addClass("clickable")
		 .click(function() { window.location="index.htm" });

	$(".redigeer").each(function(i){
		setClickable(this, i);
		})


	JT_init() //tooltips

	setupfetchedpage() // SEO => applies to articles
	setuparchcaptionlistener() //SEO
	setupfetchedanchors() // SEO => applies to reviews

});

function setClickable(obj, i) {

	$(obj).unbind().click(function() {
		var fieldname= $(obj).attr('fieldname')


		if ($(obj).attr('nrows')==undefined) var nrows=2
		else nrows= $(obj).attr('nrows')
		var br2nl = $(this).html()
//		var br2nl=br2nl.replace(/<br\/>/g, "+")
		var br2nl=br2nl.replace(/\n/g, "")
		var br2nl=br2nl.replace(/<br>/g, "\n")
		var textarea = '<div><textarea class="eip" rows="'+nrows+'" cols="60">'+br2nl+'</textarea>';
		var button	 = '<div><input type="button" value="SAVE" class="saveButton" /> OR <input type="button" value="CANCEL" class="cancelButton" /></div></div>';
		var revert = $(obj).html();
		$(obj).after(textarea+button).remove();
		$('.saveButton').click(function(){  saveChanges(this, false,  i,fieldname);});
		$('.cancelButton').click(function(){saveChanges(this, revert, i,fieldname);})
	})
	.mouseover(function() {
		$(obj).addClass("editable");
	})
	.mouseout(function() {
		$(obj).removeClass("editable");
	});
}//end of function setClickable
//===================================
function saveChanges(obj, cancel, n,fieldname) {
// this function is generic so it needs to find tablenames, fieldnames etc
// fieldnames are stored in attr of divs containing text areas which are made editable by setClickable
// tablenames can span a number of "inputs" and is stored in a parent div of class "specscontainer" as attr tablename
	var nrows=$(obj).parent().siblings(0).attr('rows')
	if(!cancel) {
		$(obj).after('<img src="tiny_red.gif">')
		var tablename=$(obj).parents('.specscontainer').attr("tablename")
		var thisrec=$(obj).parents('.specscontainer').attr("thisrec")
		var t = $(obj).parent().siblings(0).val();
		var t_clean=t.replace(/\&/g, "(ampersand)")
//		var t_clean=t.replace(/<br>/g, "\n")

//$('#postedcontent').html(t_clean)
		var poststring="content="+t_clean+"&artno="+thisrec+"&fieldname="+fieldname+"&tablename="+tablename
//$('#savedcontent').html('<textarea rows="20" cols="60">'+poststring+'</textarea>')

    		$.ajax({
   			type: "POST",
   			url: "ajq_saveart.php",
			data: poststring,
			dataType: "json",
   			success: function(jr){

   			}
 		});
		}
	else {
		var t = cancel;
	}
	if(t=='') t='(click to add text)';

	var nl2br=t.replace(/\n/g, "<br>")
	$(obj).parent().parent().after('<div class="redigeer artpara2" fieldname="'+fieldname+'" +"nrows="'+nrows+'")>'+nl2br+'</div>').remove();

	setClickable($(".redigeer").get(n), n);

}

//===================================
function saveChanges_select(obj) {
      if ($(obj).attr('id') == "searchfieldselector"){ //temp workaround, this select is excluded with .not() but still gets hooked up?
		//alert('x'+ $(obj).attr('id'))
		$(obj).unbind().change(function(){  setup_search2ndlevel_inter()  })
		 return
	}
		var t = $(obj).val();
		var tablename=$(obj).parents('.specscontainer').attr("tablename")
		var artno=$(obj).parents('.specscontainer').attr("thisrec")
		var poststring="content="+t+"&artno="+artno+"&fieldname="+$(obj).attr("name")+"&tablename="+tablename
    		$.ajax({
   			type: "POST",
   			url: "ajq_saveart.php",
			data: poststring,
			dataType: "json",
   			success: function(jr){
				t=jr.respz.message
   			}
 		});

}

function saveChanges_direct(obj) { //save whats in this object
		var t = $(obj).val();
		var tablename=$(obj).parents('.specscontainer').attr("tablename")
		var artno=$(obj).parents('.specscontainer').attr("thisrec")
		var poststring="content="+t+"&artno="+artno+"&fieldname="+$(obj).attr("fieldname")+"&tablename="+tablename
    		$.ajax({
   			type: "POST",
   			url: "ajq_saveart.php",
			data: poststring,
			dataType: "json",
   			success: function(jr){
				t=jr.respz.message
   			}
 		});

}

//===================================
function setupfetchedpage() {
				$("#getall").click(function(){getallarticles($(this).attr("articlescat"),'0')})
				$("#addrec_art").click(function(){addrec_art('articles')})
				$("#reread").click(function(){fetcharticlefor($(this).attr("artno"))})
				$("#deleterecord_art").unbind().click(function(){
						delete_art()
						}).addClass('clickable')
				$('.specscontainer').find("select").change(function(){  saveChanges_select(this)  })//.after('(*)')
				$("#logoff").click(function(){window.location="admin/logoff.php?dest=../articles.htm"})
				$('.newstop').find('.navanchoractive').each(function() {
								$(this).click(function() {
									getallarticles($(this).parents('.navspecs').attr("articlescat"),$(this).attr("step"))
									return false //SEO cancel a-tag
								})
							})
				$('.readmorelink').each(function() {
								$(this).unbind('click')
									.click(function() {
										var aid=$(this).attr("art_id")
///alert(aid)
										fetcharticlefor($(this).attr("art_id"))
										scrollTo(0,0)
										return false //SEO cancel a-tag
					 				})
									.addClass('clickable')
							 	})


				$('.calendarButton')
					.calendar({autoPopUp: 'button',
							buttonImageOnly: true,
							buttonImage: 'calendar.gif',
							buttonText: 'Calendar',
							minDate : new Date(2007, 1 - 1, 26),
							maxDate : new Date(2020, 1 - 1, 26),
							dateFormat : 'YMD/'
						})
					.change(function(){saveChanges_direct(this) });
//alert(popUpCal)
// 				try {
// 				if (popUpCal) {
// 					popUpCal.minDate = new Date(2007, 1 - 1, 26);
// 					popUpCal.maxDate = new Date(2020, 1 - 1, 26);
// 					popUpCal.dateFormat = 'YMD/';
// 				}
// 				}
// 				catch (fout) {}



				$('.commentwwnews').unbind('click')
					//tricky, for news class commentwwnews is used and usrcommentlink is now id!!
					.click(function(){
						DoenAjax_fetchcomments_div(this)
						})
					.attr('style','color:#27A6C7')

				$('#getallarts')//.html("back")
					.unbind()
					.click(function() { window.location="index.htm"} )
					.addClass('clickable')


				$('.usrcommentlink').unbind('click')  // not to be confused with id of same name in news!
					.click(function(){
						DoenAjax_fetchcomments_div(this)
						})
					.attr('style','color:#27A6C7')

				$('#centreblock').fadeIn('slow')  // in case it was hidden to show comments for reviews
				$('#commentcontainer').remove()

				$('.emailtofriend_art').unbind()
					.click(function(evt){
						$('.tellafriend').remove()
						getmailfriendform(this,evt.pageX,evt.pageY)
						})
					.addClass('clickable')


}

function fetcharticles (articlescat) {
//$('#centreblock').html('xxx')
//alert('xxx')
		if (articlescat==undefined) articlescat="art"
    		$.ajax({
   			type: "POST",
   			url: "ajq_getart.php",
			data: "articlescat="+articlescat,
			dataType: "json",
   			success: function(jr){
				$('#centreblock').html(jr.respz.html);
//$('#savedcontent').html('<textarea rows=20 cols=80>'+jr.respz.html+'</textarea>');

				setupfetchedpage();
// 				$('#homeanchor').html("articlescat="+articlescat+"&step=0")
// 					.unbind()
// 					.click(function() { getallarticles(articlescat,'0')} )

				$('#homeanchor').html("articlescat="+articlescat+"&step=0")
					.unbind()
					.click(function() { window.location="index.htm"} )

				DoenAjax_logbannerevent('page',articlescat,articlescat+'-244')

   			}
 		});
}


function fetcharticlefor(artno) {
$('#centreblock').html('<img style="float:left;margin:100 0 0 100" src="loader.gif" alt="loading...">')
          $.ajax({
   			type: "POST",
   			url: "ajq_getart.php",
			data: "artno="+artno,
			dataType: "json",
   			success: function(jr){
				$('#centreblock').html(jr.respz.html);
				$(".redigeer").each(function(i){ setClickable(this, i); })
//				prepareUploadform (this,'picform'); // maybe repeat for each picform?
				 $(".picform").each(function() {
						prepareUploadform(this,$(this).attr('id'))
					})
				setupfetchedpage()
				DoenAjax_logbannerevent('page','art',jr.respz.artcat+'261')
 			}
 		});
}

function fetcharticlefor_intovar(artno,targetdiv) {

    		$.ajax({
   			type: "POST",
   			url: "ajq_getart.php",
			data: "artno="+artno+"&editing=no",
			dataType: "json",
   			success: function(jr){
				targetdiv.append(jr.respz.html);
//mini version of setupfetchedpage, this for articles
				$('.usrcommentlink').unbind('click')
					.click(function(){
						DoenAjax_fetchcomments_div(this)
						})
					.attr('style','color:#27A6C7')


//mini version of setupfetchedpage, this for news
//tricky, for news class commentwwnews is used and usrcommentlink is now id!!
				$('.commentwwnews').unbind('click')
					.click(function(){
						DoenAjax_fetchcomments_div(this)
						})
					.attr('style','color:#27A6C7')


				$('#getallarts') // actually home anchor
					.unbind()
//					.click(function() { getallarticles_url($('#homeanchor').html())} )
					.click(function() { window.location="index.htm"} )
					.addClass('clickable')

				$('.readmorelink').hide()

				DoenAjax_logbannerevent('page','arch',jr.respz.artcat+'261')
 			}
 		});
}


function fetcharticleforpic(picname) {
//	DoenAjax_logbannerevent('page','art')
    		$.ajax({
   			type: "POST",
   			url: "ajq_getart.php",
			data: "picname="+picname,
			dataType: "json",
   			success: function(jr){
				$('#centreblock').html(jr.respz.html);
				$("#addrec_art").click(function(){addrec_art('articles')})
 				$(".redigeer").each(function(i){
					setClickable(this, i);
					})
				 $(".picform").each(function() {prepareUploadform(this,$(this).attr('id'))})
				setupfetchedpage()
				DoenAjax_logbannerevent('page','art','285')
  			}
 		});
}


function getallarticles(articlescat,step) {// removed getall=yes&  from post var to limit only to active
    		$.ajax({
   			type: "POST",
   			url: "ajq_getart.php",
			data: "step="+step+"&articlescat="+articlescat ,
			dataType: "json",
   			success: function(jr){
				$('#centreblock').html(jr.respz.html);
				$('.artcaption').each(function() {
							$(this).click(function() { fetcharticlefor($(this).attr("art_id"))
							 				})
							 	.addClass("clickable")
							 	})
				setupfetchedpage()
				$('#homeanchor').html("articlescat="+articlescat+"&getall=yes&step="+step)
					.unbind()
					.click(function() { getallarticles(articlescat,step)} )
					.addClass('clickable')

				DoenAjax_logbannerevent('page','art','302')
   			}
 		});
}


function getallarticles_url(url) {
    		$.ajax({
   			type: "POST",
   			url: "ajq_getart.php",
			data: url ,
			dataType: "json",
   			success: function(jr){
				$('#centreblock').html(jr.respz.html);
				$('.artcaption').each(function() {
							$(this).click(function() { fetcharticlefor($(this).attr("art_id"))
							 				})
							 	.addClass("clickable")
							 	})
				setupfetchedpage()
				DoenAjax_logbannerevent('page','art','302')
   			}
 		});
}



function DoenAjax_fetchcomments_div(obj) {
		var artno=$(obj).parents('.specscontainer').attr("thisrec")

		DoenAjax_fetchcomments_artno(artno,'a')
}

function DoenAjax_fetchcomments_div_rvw(obj) {
		var artno=$(obj).parents('.specscontainer').attr("thisrec")
		DoenAjax_fetchcomments_artno(artno,'r')
}

function DoenAjax_fetchcomments_artno (artno,art_rvw) {
		var poststring="artno="+artno+"&art_rvw="+art_rvw //article or review or event, get form too
					// for articles, get extract from article
					// for reviews, ...
					// for events, ...
					// ... maybe save #rvwfrag and restore after ajax success
    		$.ajax({
   			type: "POST",url: "ajq_getusercomment.php",
			data: poststring,
			dataType: "json",
   			success: function(jr){

				$('#centreblock')
					.after('<div id=commentcontainer>'+jr.respz.html+'</div>')
					.fadeOut('slow',function(){restorefrag(art_rvw)})
				restorefrag(art_rvw)
				$('.goback')
					.unbind("click")
					.click(function() {
								$('#centreblock').fadeIn('slow')
								$('#commentcontainer').remove()
							})
					.addClass("clickable")
					.end()
				.find("#usercommentform")
				.submit(function(){
					submitusercommentform(this,"centreblock")
					return false;
					})
				.find("textarea").html("your comment here")
				.end()
				.find("#preview").unbind('click')
					.click(function(){previewtusercommentform()})
					.val("Preview")
				scrollTo(0,0)

   			}
 		});
}
//==============
function previewtusercommentform(formobj,targetdiv) {
 	var ta=$("#usercommentform").find("textarea")
 	var cntnt=$(ta).val()
	$(ta).after('<div class="commenttext">'+cntnt+'</div>').fadeOut('slow')
	$("#usercommentform").find("#preview")
				.unbind('click')
				.click(function(){	$(ta).fadeIn('slow')
								$('.commenttext').remove()
								$(this).unbind('click')
										.click(function(){previewtusercommentform()})
										.val("Preview")
							})
				.val("Edit again")

}

//==============

function restorefrag(art_rvw) {
	if (sfrag!="") {
		if ((art_rvw=="r") || (art_rvw=="e")) {
			$('#rvwfragment').html(sfrag)
			sfrag=""
//  		logthis (lyn+"(pic):"+sfrag)

		}
	}
}

//===== === === ===
function submitusercommentform(formobj,targetdiv) {
	sfrag=$('#rvwfragment').html()  // temp storage buffer, declared in beginning
	$('#commentcontainer').remove()  //why? ==> because new one is created

 	var poststr=$(formobj).formSerialize()+"&targetdiv="+targetdiv+"&table=usercomment"
 		$.ajax({
   			type: "POST",
   			url: "ajq_saveusrcomment.php",
			data: poststr,
			dataType: "json",
   			success: function(jr){

				DoenAjax_fetchcomments_artno (jr.respz.ref_id,jr.respz.art_rvw)
					//fetches form to submit too, with ref_id
					// puts up rvwfragment div, filled for art, empty for rvw and evt
					// although comments are the same across art/review/events, the accompanying
					// art/rvw/cmt content are not, therefore pass on art_rvw field
				if ((jr.respz.art_rvw=="r") || (jr.respz.art_rvw=="e")) {
					logthis(lyn+": restoring #rvwfragment after fetching "+jr.respz.ref_id+"&bull;"+jr.respz.art_rvw)
					lyn++
				}
   			}
 		});

}
