var daterange_disable_text = false;
var daterange_disable_digi = false;

function disableadvanced( disable ) {
  $('headline').disabled  = disable;
  $('byline').disabled  = disable;
}

function disabledaterange( ctl ) {
  disable = (ctl.value == 'custom' ? false : true);
	searcharea = "";
	if (ctl.form.name.match(/^search_/))
		searcharea = ctl.form.name.replace(/^search_/,"");
  if ($('daterange_select_' + searcharea))
		$('daterange_select_' + searcharea).style.display = (disable?"none":"block");
	disabledateselect( ctl.form, disable );

  eval("daterange_disable_"+searcharea+"="+disable+";");
}

function disabledateselect( theform, disable ) {
  theform.day1.disabled  = disable;
  theform.mon1.disabled  = disable;
  theform.year1.disabled = disable;
  theform.day2.disabled  = disable;
  theform.mon2.disabled  = disable;
  theform.year2.disabled = disable;
}

function $(id) {
	return document.getElementById( id );
}

function getIncludeList( item ) {
	var list = "";
	for (var i in subsectionlist_unselected) {
		if (subsectionlist_unselected[i] == 0) list += i + ",";
	}
	return (list.length > 0 ? list+item : item);
}

function getExcludeList( item ) {
	var list = "";
	for(var i in subsectionlist_unselected) {
		if (i != escape(item) && subsectionlist_unselected[i] == 0)
			list += i + ",";
	}
	return list.substring( 0, list.length-1 );
}

function findPos(obj) {
  curwidth  = obj.offsetWidth;
  curheight = obj.offsetHeight;

  var curleft = curtop = 0;
  if (obj.offsetParent) {
    curleft = obj.offsetLeft
    curtop = obj.offsetTop
    while (obj = obj.offsetParent) {
      curleft += obj.offsetLeft
      curtop += obj.offsetTop
    }
  }

  return [curleft,curtop,curleft+curwidth,curtop+curheight];
}

function showPopUpMenu(item, section, section_display, count) {
  //alert( findPos( item ) );
  var pos = findPos( item );
  l = pos[0];
  t = pos[1];
  r = pos[2];
  b = pos[3];

  l1 = l - parseInt($(popupprefix+'subitem').style.width);
  t1 = t;
  b1 = t + parseInt($(popupprefix+'subitem').style.height );
  r1 = l;

  resetList();

  item.className = popupprefix+'item_active';
  $( popupprefix+'subitem' ).style.left = (l1 + 1) + "px";
  $( popupprefix+'subitem' ).style.top  = (t  + 1) + "px";
  $( popupprefix+'subitem' ).style.display= 'block';

	/*
  $('debug').innerHTML = "(t=" + t + " l=" + l + " b=" + b + " r=" + r + ");";
  $('debug').innerHTML += "(" + t1 + " " + l1 + " " + b1 + " " + r1 + ")";
  $('debug').innerHTML += $( popupprefix+'subitem' ).style.width + " ";
  $('debug').innerHTML += $( popupprefix+'subitem' ).style.height + " ";
	*/
  document.onmousemove = trackmouse;

  activeitem = item;

	var positivecount = 0;
	var negativecount = 0;
	for (var item in subsectionlist_unselected) {
		if (subsectionlist_unselected[item] == 1) negativecount++
		else positivecount++;
	}

	//var h = parseInt($( popupprefix+'subitem' ).style.height) - (b - t) + 2;
	//var h = parseInt($( popupprefix+'subitem' ).style.height) - (b - t);
	//$(popupprefix+'popuprightborder').style.height = h;

	$(popupprefix+'popuptitle').innerHTML = section_display;

	$(popupprefix+'popuprefinelink').style.display = 'none';
	$(popupprefix+'popupexcludelink').style.display = 'none';
	$(popupprefix+'popupincludelink').style.display = 'none';

	//var html = section_display + "(p=" + positivecount +",n="+negativecount + ")<hr/>";
	//html += "(t=" + t + " l=" + l + " b=" + b + " r=" + r + ")<br/>";

	if (subsectionlist_unselected[ escape(section) ] == 0) {
		if (negativecount == 0) {
			$(popupprefix+'popuprefinelink').href = baseurl+"&amp;"+popupparam+"="+section;
			$(popupprefix+'popuprefinelink').style.display = 'block';
		}
		$(popupprefix+'popupexcludelink').href = baseurl+"&amp;"+popupparam+"="+getExcludeList(section);
		$(popupprefix+'popupexcludelink').style.display = 'block';
	} else {
		$(popupprefix+'popupincludelink').href = baseurl+"&amp;"+popupparam+"="+getIncludeList(section);
		$(popupprefix+'popupincludelink').style.display = 'block';
	}
}

function resetList() {
  var list = document.getElementsByTagName('li');
  for(var i=0;i<list.length;i++) {
    if (list[i].className == popupprefix+'item_active')
      list[i].className = popupprefix+'item';
  }
}

function trackmouse(e) {

	var xcoord, ycoord;
  if( !e ) { e = window.event; }
  if( !e ) { return; }
  if( typeof( e.pageX ) == 'number' ) {
    xcoord = e.pageX;
    ycoord = e.pageY;
  } else if( typeof( e.clientX ) == 'number' ) {
    xcoord = e.clientX;
    ycoord = e.clientY;
    if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
      xcoord += document.body.scrollLeft;
      ycoord += document.body.scrollTop;
    } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
      xcoord += document.documentElement.scrollLeft;
      ycoord += document.documentElement.scrollTop;
    }
  } else { return; }

  //$('coords').innerHTML = "x= "+xcoord+", y= "+ycoord;

  if (ycoord >= t1 && ycoord <= b1 && xcoord >= l1 && xcoord <= r1) {
    //$('coords').innerHTML += " [IN]";
    return;
  }
  if (ycoord >= t && ycoord <= b && xcoord >= l && xcoord <= r) {
    //$('coords').innerHTML += " [IN]";
    return;
  }

  //$('coords').innerHTML += " [OUT]";

  activeitem.className= popupprefix+'item';
  $(popupprefix+'subitem').style.display= 'none';
  document.onmousemove = null
}

function $( id ) {
  return document.getElementById( id );
}
function movemouse(e) {
	var yyyymm, datetype, idx;

  if (isdrag) {
    offset = nn6 ? tx + e.clientX - x : tx + event.clientX - x;
    w = parseInt( dobj.style.width );
		
		if (dobj.getAttribute('id') == 'span1') {
			w -= (lastoffset - offset);
			max = totalwidth - parseInt( $('span2').style.width );
			idx = parseInt( w / (barwidth+1) );
			datetype = 'from';
		} else  if (dobj.getAttribute('id') == 'span2') {
			w += (lastoffset - offset);
			max = totalwidth - parseInt( $('span1').style.width );
			idx = parseInt( datelist.length - (w / (barwidth+1)) );
			datetype = 'to';
		}

		//console.log( "totalwidth = " + totalwidth);
		//console.log( "idx = " + idx );
		if (w <= parseInt(barwidth/2) || w > max) return false;

		yyyymm = datelist[ idx ];

		if (idx == datelist.length-1) { // Last Item?
			//console.log( "last item= " + origdatelist[ origdatelist.length-1 ]);
			yyyymm = "" + origdatelist[ origdatelist.length-1 ];
		}

		yy = yyyymm.substring(0,4);
		mm = yyyymm.substring(4,6).replace(/^0/,""); // Avoid being read as octal
		dd = (datetype == 'from'?1:daysinmonth(yy, mm));

		yearctl = document.searchform.elements['year'+(datetype=='from'?1:2)];
		monctl = document.searchform.elements['mon'+(datetype=='from'?1:2)];
		dayctl = document.searchform.elements['day'+(datetype=='from'?1:2)];

		selectOption( yearctl, yy);
		selectOption( monctl,  mm);
		selectOption( dayctl,  dd);
		mmname = monctl.options[ monctl.selectedIndex ].text;
		mmname = mmname.substring(0,3);

		dobj.title = mmname + "/" + yy + "(" + origgrouped_valuelist[ idx ] + ")";

		$('tooltip').innerHTML = "<b>Date:</b> " + mmname
			+ "/" + yy + "<br/>\n" + "<b>Hits:</b> " + origgrouped_valuelist[ idx ];
		$('tooltip').style.visibility = "visible";

    dobj.style.width = w + "px";

		lastoffset = offset;

    return false;
  }

	$('tooltip').visibility = 'hidden';
	$('tooltip').innerHTML  = '';
	
}

function daysinmonth(year, month) {
	daylist = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
	return (month == 2 && isleapyear(year) ? 29 : daylist[month-1]);
}
function isleapyear(year) {
	return (year%4 == 0 && year%100 != 0 && year%400 == 0 ? true : false);
}

function selectOption( ctl, val ) {

	var opts = ctl.options;
	for(var i=0;i<=opts.length;i++) {
		if (parseInt(opts[ i ].value) == parseInt(val)) {
			ctl.selectedIndex = i;
			return;
		}
	}

}

function selectmouse(e) {
  var fobj       = nn6 ? e.target : event.srcElement;
  var topelement = nn6 ? "HTML" : "BODY";

  while (fobj.tagName != topelement && fobj.className != "dragme") {
    fobj = nn6 ? fobj.parentNode : fobj.parentElement;
  }

  if (fobj.className=="dragme") {
    isdrag = true;
    dobj = fobj;
    tx = parseInt(dobj.style.left+0);
    ty = parseInt(dobj.style.top+0);
    x = nn6 ? e.clientX : event.clientX;
    y = nn6 ? e.clientY : event.clientY;
    lastoffset = nn6 ? tx + e.clientX - x : tx + event.clientX - x;
    document.onmousemove=movemouse;
    return false;
  }
}



function initdaterange() {

	origgrouped_valuelist = valuelist.slice();

	var ratio = graphheight / max;
	//console.log( ratio );
	//console.log( valuelist );
	for (var i=0; i<valuelist.length; i++) {
		valuelist[ i ] = parseInt( valuelist[ i ] * ratio );
		if (valuelist[ i ] > 0 && valuelist[ i ] < 3) {
			valuelist[ i ] = 3;
		}
	}
	//console.log( valuelist );

	document.onmouseup = function() { isdrag = false; };

	yyctl = document.searchform.year1;
	mmctl = document.searchform.mon1;
	yy = yyctl.options[ yyctl.selectedIndex ].value;
	mm = parseInt( mmctl.options[ mmctl.selectedIndex ].value );
	s_yymm = yy + (mm<10?"0":"") + mm;

	yyctl = document.searchform.year2;
	mmctl = document.searchform.mon2;
	yy = yyctl.options[ yyctl.selectedIndex ].value;
	mm = mmctl.options[ mmctl.selectedIndex ].value;
	e_yymm = yy + (mm<10?"0":"") + mm;

	s_pos = parseInt(barwidth/2);
	e_pos = parseInt(barwidth/2);

	//console.log( 's_yymm = ' + s_yymm );
	//console.log( 'e_yymm = ' + e_yymm );

	var pos = 0;
	for(i=0; i<datelist.length; i++) {

		var h = (valuelist[i] == 0 ? 0 : valuelist[i]-1);
		var style = "height: " + h + "px; left: " + pos + "px";
		var title = datelist[i] + "(" + valuelist[i] + ")";

		if (i > 0) pos+=1;

		var element;
		element = document.createElement("div");
		element.className = "bar";
		element.title = title;
		element.style.height = h + "px";
		element.style.left = pos + "px";
		if (h == 0) element.style.visibility = "hidden";
		$('graph').appendChild( element );

		//console.log("isindaterange( '"+datelist[i]+"',"+ s_yymm +")) " + (isindaterange( datelist[i], s_yymm )?"true":"false"));
		//if (datelist[i] == s_yymm) {
		if (i != 0 && isindaterange( datelist[i], s_yymm )) {
			s_pos = pos + parseInt(barwidth/2)
		}
		//console.log("isindaterange( '"+datelist[i]+"',"+ e_yymm +")) " + (isindaterange( datelist[i], e_yymm )?"true":"false"));
		//if (datelist[i] == e_yymm) {
		if (i != datelist.length-1 && isindaterange( datelist[i], e_yymm )) {
			e_pos = totalwidth - pos - parseInt(barwidth/2)
		}

		//console.log( 'datelist[i] = ' + datelist[i] );

		pos+=barwidth;
	}

	$('daterangeslider').style.height = (graphheight+4) + "px";
	//$('daterangeslider').style.width  = totalwidth+4 + 'px';
	$('daterangeslider').style.width  = pos + "px";

	var allPageTags=document.getElementsByTagName("div"); 
	for (i=0; i<allPageTags.length; i++) {
		if (allPageTags[i].className == 'bar') {
			allPageTags[i].style.width = barwidth + 'px';
		}
	}

	$('span1').style.width = s_pos + "px";
	$('span2').style.width = e_pos + "px";

	if (! datelist.length > 0)
		$('daterangeslider').style.display = "none";
	
}

function isindaterange( range, mydate) {

	if (range.indexOf( ',' ) == -1)
		return (range == mydate ? true : false);

	var myrange = range.split( ',' );

	//console.log( mydate + " >= " + myrange[0] + " && " + mydate + " <= " + myrange[1] );

	if (parseInt( mydate ) >= parseInt(myrange[0]) && parseInt(mydate) <= parseInt(myrange[1]) ) {
		//console.log( "isindaterange( " + range + ", " + mydate + " ) returns true" );
		return true;
	}

	//console.log( "isindaterange( " + range + ", " + mydate + " ) returns false" );
	return false;

}

function groupdatelist() {

	// Skip if it fits...
	if (maxwidth/datelist.length > barwidth) return;

  //var maxvaluelist = valuelist.slice();
  //maxvaluelist.sort(function (a,b) { return b - a });
	//console.log( maxvaluelist[ 0 ] );

	var slots = maxwidth / (barwidth+1);
  var groupsize = Math.round( datelist.length / slots );
	//console.log( "groupsize = " + groupsize );

  var grouped_datelist = new Array();
  for(var i=0;i<=datelist.length;i+=groupsize) {
    end = (i+groupsize-1>=datelist.length?datelist.length-1:i+groupsize-1);
    grouped_datelist.push( datelist[ i ] + "," + datelist[ end ] );
  }

  var grouped_valuelist = new Array();
  var total;
  for(var i=0;i<=valuelist.length;i+=groupsize) {
    end = (i+groupsize-1>=valuelist.length?valuelist.length-1:i+groupsize-1);

    total = 0;
    for(var j=i;j<=end;j++) {
      total += parseInt( valuelist[ j ] );
    }
    //grouped_valuelist.push( Math.round( total/groupsize ) );
    grouped_valuelist.push( total );
  }

	//console.log( valuelist );
	//console.log( grouped_valuelist );

  valuelist = grouped_valuelist;
  datelist  = grouped_datelist;
}

function resetDates() {
	theForm = document.searchform;
	theForm.year1.selectedIndex = 0;
	theForm.mon1.selectedIndex = 0;
	theForm.day1.selectedIndex = 0;

	theForm.year2.selectedIndex = theForm.year1.options.length - 1;
	var today = new Date();
	theForm.mon2.selectedIndex = today.getMonth();
	theForm.day2.selectedIndex = today.getDate() - 1;

	initdaterange();

}

function initForm(ctl) {
  for(var i = 0; i < ctl.length; i++) {
    if(ctl[i].checked && ctl[i].value == 'custom') {
      ctl[i] = true;
      disabledaterange( ctl[i] );
    }
  }
}
