/***
 *
 * rubberband.js
 * rubber band selection routines
 * adapted from http://home.earthlink.net/~wzd3/rubberband.html
 *
 * requires gr.js
 ***/

var gr = new Graphics("canvas");
var c = null;
var divadded;
// setup mouse capturing
// 
// http://www.breakingpar.com/bkp/home.nsf/Doc?OpenNavigator&U=87256B14007C5C6A87256B4B0005BFA6
// Set Netscape up to run the "captureMousePosition" function whenever
// the mouse is moved. For Internet Explorer and Netscape 6, you can capture
// the movement a little easier.

if (document.layers) { // Netscape
    document.captureEvents(Event.MOUSEMOVE);
    document.onmousemove = captureMousePosition;
} else if (document.all) { // Internet Explorer
    document.onmousemove = captureMousePosition;
} else if (document.getElementById) { // Netcsape 6
    document.onmousemove = captureMousePosition;
}

// Global variables
var xMousePos = 0; // Horizontal position of the mouse on the screen
var yMousePos = 0; // Vertical position of the mouse on the screen

function captureMousePosition(e) {
  if (document.layers) {
    // When the page scrolls in Netscape, the event's mouse position
    // reflects the absolute position on the screen. innerHight/Width
    // is the position from the top/left of the screen that the user is
    // looking at. pageX/YOffset is the amount that the user has
    // scrolled into the page. So the values will be in relation to
    // each other as the total offsets into the page, no matter if
    // the user has scrolled or not.
    xMousePos = e.pageX;
    yMousePos = e.pageY;
  } else if (document.all) {
    // When the page scrolls in IE, the event's mouse position
    // reflects the position from the top/left of the screen the
    // user is looking at. scrollLeft/Top is the amount the user
    // has scrolled into the page. clientWidth/Height is the height/
    // width of the current page the user is looking at. So, to be
    // consistent with Netscape (above), add the scroll offsets to
    // both so we end up with an absolute value on the page, no
    // matter if the user has scrolled or not.
    var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
    xMousePos = window.event.x + scrollLeft;
    yMousePos = window.event.y + scrollTop;
  } else if (document.getElementById) {
    // Netscape 6 behaves the same as Netscape 4 in this regard
    xMousePos = e.pageX;
    yMousePos = e.pageY;
  }
}

var divX1;
var divX2;
var divY1;
var divY2;
var drawing = false;
var startX = 0;
var startY = 0;
var p = null;
var a = 0;
var selX2=new Array();
var selY2=new Array();
var selWid2=new Array();
var selHt2=new Array();
var x1 ;
var x2 ;
var y1 ;
var y2 ;
var sts=0;
var w;
var h;

var selleft;
var seltop;
var selw;
var selh;

var pixelsold=new Array();
var compix;
var tblleft;
function startLine(sel_X1,sel_Y1,sel_Wid,sel_Ht){

  // alert(sel_X1 + ".." + sel_Y1 + ".." + sel_Wid + ".." +sel_Ht)
  var canvas = document.getElementById('canvas');
  tblleft=document.getElementById("maintable");

  divX1 = canvas.offsetLeft ;
  divY1 = canvas.offsetTop ;
  divX2 = divX1 + canvas.offsetWidth ;
  divY2 = divY1 + canvas.offsetHeight;
  startX= (xMousePos-divX1);
  startY= (yMousePos-divY1);
   
   /* bdr_X1 = divX1 + tblleft.offsetLeft;
	bdr_X2 = divX2 + tblleft.offsetLeft;*/
	bdr_X1 = divX1;
	bdr_X2 = divX2;
	
	/*bdr_Y1 = divY1 + 79 + 90;
	bdr_Y2 = divY2 + 79 + 90;*/
	bdr_Y1 = divY1  ;
	bdr_Y2 = divY2  ;
  
  
  	selX2=sel_X1.split("-");
	selY2=sel_Y1.split("-");
	selWid2=sel_Wid.split("-");
	selHt2=sel_Ht.split("-");
	//alert(selX2[0]);
	drawing = true;
	//alert(selX2);
	 var frm=document.graffiti;
	// alert(sts);
	
	sts=0;
	 drawBand();
	/*if(sts!=2){
	if(ischeckavailability()){
		sts=0;
    	drawBand();
	}
	else{
		sts=1;
		alert("Cant overlap over a existing image");
		//location.reload(true);
		//gr.removeShape(p);
		//frm.submit();
    }
	}else{
		sts=0;
    	drawBand();
	}*/
  
}

function stopLine(){
		var frm=document.graffiti;
  		drawing = false;
		/*if(ischeckavailability())
		sts=0;
		else
		sts=1;*/
		if(ischeckavailability()){
			var answer = confirm("Do you want to proceed for payment")
			if (answer){
				frm.method="post";
				frm.action="pixels_link.php";
				 frm.submit();
			}
			else{
				sts=0;
				return false;
			}
		}
                 else{
			sts=0;
			// alert(xMousePos +"<"+ divX1 +"||"+ xMousePos +"<"+ bdr_X1 +"||"+  xMousePos +">"+ bdr_X2 +"||"+ yMousePos +"<"+ divY1 +"||"+ yMousePos +"<"+ bdr_Y1 +"||"+ yMousePos +">"+ bdr_Y2);
			alert("Cant overlap over a existing image");
			//location.reload(true);
			var country=document.getElementById("country").value;
			if(country=="" || country=="United_States" ){
				location.href="pixels.php?state="+document.getElementById("state").value+"&county="+document.getElementById("county").value+"&country=United_States";
			}else{
				location.href="pixels.php?country="+document.getElementById("country").value;
				//location.href="www.greenstumps.com";
			}
			gr.removeShape(p);
			
			return false;
		}
	
  
}

function drawBand()
{

  // leave band alone if out of range
 	 if (xMousePos < divX1 || xMousePos < bdr_X1 ||  xMousePos > bdr_X2 || yMousePos < divY1 || yMousePos < bdr_Y1 || yMousePos > bdr_Y2 ||  !ischeckavailability()){  //
		window.setTimeout("drawBand();", 1);
		return;
	  }
 
  // don't redraw band if mouse is up
  if (drawing == false) 
    return;

  // remove previous band
  if (p)
    gr.removeShape(p);

  gr.penColor = "#FF4040";

  // compute the exact rectangle from start point to mouse point
  var x1 = startX;
  var x2 = xMousePos - divX1;
  var y1 = startY;
  var y2 = yMousePos - divY1;

  // adjust so x1, y1 is UL corner
  var temp;
  var swap_x = false;
  if (x2 < x1) { temp = x1; x1 = x2; x2 = temp; swap_x = true; }
  var swap_y = false;
  if (y2 < y1) { temp = y1; y1 = y2; y2 = temp; swap_y = true; }

  // now adjust it to cover whole 10x10 blocks
  x1 = Math.floor(x1 / 10) * 10;
  y1 = Math.floor(y1 / 10) * 10;
  x2 = Math.ceil(x2 / 10) * 10;
  if (x2 == x1) x2 += 10;
  if (x2 > divX2 - divX1) { x1 -= 10; x2 -= 10; }
  
  
  
  y2 = Math.ceil(y2 / 10) * 10;
  if (y2 == y1) y2 += 10;
  if (y2 > divY2 - divY1) { y1 -= 10; y2 -= 10; }

  // compute region width, height
  w = x2 - x1;
  h = y2 - y1;

  var f = document.forms[0];
  var pixels_text = 'pixels';

  if (f) {
    // constrain region to max_w, max_h limits
    if (f.max_w && f.max_w.value > 0)
      w = Math.min(w, Math.ceil(f.max_w.value / 10) * 10);
    if (f.max_h && f.max_h.value > 0)
      h = Math.min(h, Math.ceil(f.max_h.value / 10) * 10);

    // make sure anchor point does not move
    if (swap_x) x1 = x2 - w;
    if (swap_y) y1 = y2 - h;

    // set form values
    f.x.value = x1
    f.y.value = y1
    f.w.value = w
    f.h.value = h
	f.pixs.value=(w*h);
	f.amt.value=(w*h)/10;
	
	selleft = x1;
	seltop = y1;
	selw = w;
	selh = h;
	
    if (f.pixels_text)
      pixels_text = f.pixels_text.value;
	  
	  var canvas = document.getElementById('canvas');
	//canvas.title=w+"X"+h+" Pixels : "+w*h+" Price : $"+amt ;
	amt=(w*h)/10;
	canvas.title=w+"px X"+h+"px, Selected Pixels : "+w*h+"px, Price : $"+amt ;
  }

  // update selection description
  var sel = document.getElementById('selection');
  if (sel) {
    var siz = w * h;
    siz = siz.toString();
    var amt = '';
    if (f) {
      if (f.thousands_separator) {
        while (siz.match(/\d\d\d\d$/))
          siz = siz.replace(/(\d)(\d\d\d)$/, '$1 $2');
        siz = siz.replace(/ /g, f.thousands_separator.value);
      }
      if (f.pixel_price && f.pixel_price.value > 0) {        
        square =  w * h;
        if (f.allow_free_paid.value == "true" && f.free_square.value >= square) square = 0;
        amt = square * f.pixel_price.value;
        amt = amt.toFixed(2);
     /*   if (f.decimal_point)
          amt = amt.replace(/\./g, f.decimal_point.value);*/
        if (f.thousands_separator) {
          while (amt.match(/\d\d\d\d\D/))
            amt = amt.replace(/(\d)(\d\d\d\D.*)/, '$1 $2');
          amt = amt.replace(/ /g, f.thousands_separator.value);
        }
        if (f.currency_symbol)
          amt = f.currency_symbol.value + amt;
        amt = ', ' + amt;
      }
    }
   var html = '(' + w + ' x ' + h + '), ' + siz + ' ' + pixels_text + amt;
    sel.innerHTML = html;
	/* canvas.title=w+"X"+h+" Pixels : "+w*h+" Price : $"+amt ;*/
	
  }
	y1=y1;
	h=h;
	//document.getElementById("mouseleft").value=x1+","+ y1+","+ w+","+ h ;
  p = gr.drawRectangle(x1, y1, w, h);
  window.setTimeout("drawBand();", 1);
}

function moveCanvas(to_id)
{
  var to = document.getElementById(to_id);
  var canvas = document.getElementById('canvas');
  var pos = getPos(to);
  canvas.style.left = pos.x + 'px';
  canvas.style.top = pos.y + 'px';
  canvas.style.visibility = 'visible';
}

// get absolute position of element
// from http://www.alphafilter.com/?inc=article&aid=30
function getPos(el) {
  var p = YAHOO.util.Dom.getXY(el);
  var pos = new Object;
  pos.x = p[0];
  pos.y = p[1];
  return pos;
}


function ischeckavailability(){
		var top2 = seltop;
		var left2 = selleft;
		var right2 = left2 + selw;
		var bottom2 = top2 + selh;
        var old=document.getElementById("old");
		var new1=document.getElementById("new");
		var pos =0;
		
	for(che=0;che<selX2.length;che++){
			var right1=parseInt(selX2[che])+parseInt(selWid2[che]);
			var bottom1=parseInt(selY2[che])+parseInt(selHt2[che]); 

           // var right2 = left2+parseInt(selWid2[che])
           // var bottom2 = top2+parseInt(selHt2[che])
            
			// alert("right1=" + right1 + "...right2=" + right2 + "...bottom1=" + bottom1 + "...bottom2=" + bottom2 + "...left2=" + left2 + "...top2=" + top2 + "...selX2[che]="+Number(selX2[che])+"...selY2[che]="+Number(selY2[che])+"...selWid2[che]="+Number(selWid2[che])+"...selHt2[che]="+Number(selHt2[che]));
                        
			if(selX2[che] && selY2[che] && right1 && bottom1){
				sts=0;
				/* if(yMousePos>Number(selY2[che]) &&  yMousePos<(Number(selY2[che])+Number(selHt2[che])-160)){
								return false;	
						  }
				if(xMousePos>Number(selX2[che]) && xMousePos<(Number(selX2[che])+Number(selWid2[che]))){
							 	return false;
				}
				if(right2>Number(selX2[che]) && right2<Number(right1)){
							 	return false;
				}
				if(bottom2>Number(selY2[che]) && bottom2<Number(bottom1)){
								return false;	
				}  */
			 if(bottom2>Number(selY2[che]) && top2<bottom1){
				
			   // if(right2 == Number(selX2[che]) || left2 == right1  || bottom2==Number(selY2[che]) || top2==bottom1){
                           if(right2 == right1 || left2 == Number(selX2[che]) || bottom2==Number(selY2[che]) || top2==bottom1){
                             
				 	 /*sts=1;
					alert("Cant overlap over a existing image");*/
                   // alert('1')
                  //  alert(right2 + ".." + Number(selX2[che]) + ".." + left2 + ".." + right1 + ".." + bottom2 + ".." + Number(selY2[che]) + ".." + top2 + ".." + bottom1)
				return false;
			   }
			  }
			  if(right2>Number(selX2[che]) && left2<right1){
				// if(bottom2==Number(selY2[che]) || top2==bottom1){
                                if(bottom2==bottom1 || top2==Number(selY2[che])){
                	//alert('2')
                    //alert(bottom2 + ".." + Number(selY2[che]) + ".." + top2 + ".." + bottom1)
                    return false;
			   }  
			  }
			   if(left2<Number(selX2[che])){
				   if(top2>Number(selY2[che]) && top2<bottom1){
					if(right2>(Number(selX2[che]))){
					
				return false;
					}
				   }
				}
			    else if(left2>right1){
					if(top2>Number(selY2[che]) && top2<bottom1){
						if(right2<(right1)){
						
				return false;
						}
					}					
				}
			    else{
					if(top2<Number(selY2[che]) && top2>bottom1){
						
				return false;
					}					
			    }
				
				if(top2<Number(selY2[che])){
					if(left2>Number(selX2[che]) && left2<right1){
						if(bottom2>bottom1)	
							
				return false;
					}
					
				}
				else if(top2>(Number(selY2[che])) && top2<bottom1){
					if(left2>(Number(selX2[che])) && left2<right1){
							
				return false;					
					}
					
				}
			old.value=selX2[che] + "~" + selY2[che] + "~" + right1 + "~" + bottom1;
			new1.value=left2 + "~" + top2 + "~" + right2 + "~" + bottom2;
		  }				  
	    }
	sts=1;
	return true;

}

function getSign(v) {
    if(v > 0) return "+";
    else if(v < 0) return "-";
    else return 0;
  }

function check_availablePixels(){
		var top2 = seltop;
		var left2 = selleft;
		var right2 = left2 + selw;
		var bottom2 = top2 + selh;
		var j;
		var k;
		//compix.split("~");
		
		/*alert(top2+"~"+left2+"~"+selw+"~"+selh);
		return false;*/
		for(j=left2; j<=(Number(left2)+Number(selw)); j++){
				for(k=top2; k<=(Number(top2)+Number(selh)); k++){
					//alert(k);
					document.getElementById("testcom").value=document.getElementById("testcom").value+"#"+j+"@"+k;
					if(compix.match(j+"@"+k)){
						//alert("match found");
						return false;
					}
					
				}
			}
			
			return true;
}
