function getCookieVal (offset) {
    var endstr = document.cookie.indexOf (";", offset);
    if (endstr == -1)
        endstr = document.cookie.length;
    return unescape(document.cookie.substring(offset, endstr));
}

function GetCookie (value) {
    var name = value + "=";
    var len  = name.length;
    var lenCookie = document.cookie.length;
    var i = 0;
    while (i < lenCookie) {
        var j = i + len;
        if (document.cookie.substring(i, j) == name)
            return getCookieVal (j);
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0)
            break;
    }
    return null;
}

function GetMyCookie (cookie_name, default_value) {
  var sPage = GetCookie(( isDsk() ? '' : 'app') + cookie_name);
  return (sPage ? sPage : default_value);
}

function SetMyCookie (cookie_name, value) {
  var expires = new Date ();
  expires.setTime(expires.getTime() + (366 * 24 * 3600 * 1000)); //cookie expires after a year

  var name = ( isDsk() ? '' : 'app') + cookie_name;
  document.cookie = name + "=" + value + "; expires=" + expires.toGMTString();
}

function space(w, h) {
  //simple clear spacer for positioning table cells
  return '<img src=space.png border=0 width='+w+' height='+h+' />';
}

function CoverClick (upc, front, thumb, f) {
  var side = (front ? 'f' : 'b');
  var dir = (thumb ? 'thumbs/' : 'covers/');
  var h = (thumb ? ' height='+thumbHeight : (fullHeight != '' ? ' height='+fullHeight : ''));
  var w = (thumb ? ' width='+thumbWidth : (fullWidth != '' ? ' width='+fullWidth : ''));
  if (f != '') {
    f = ' onclick="' + f + ';"';
  }
  return '<img src='+dir+upc+side+'.jpg'+w+h+' border=0' + f + '>';
}

function Cover (upc, front, thumb) {
  return CoverClick(upc, front, thumb, '');
}

function AnchorUrl(aUPC, aSort, aIdx, aQry, aX, aY, aZ, aM, aF, aD) {
  //append all the parameters together into my standard url format
  var theUrl = aUPC != '' ? aUPC : 'search.php';
  return theUrl+'?sorturl='+aSort+'&sortidx='+aIdx+'&dvdqry='+aQry+'&dvdx='+aX+'&dvdy='+aY+'&dvdz='+aZ+'&dvdm='+aM+'&fontx='+aF+'&fixed='+aD;
}

function Anchor(url, disp, title, external) {
  if (title != '') {
    title = ' title="'+title+'"';
  }
  if (external) {
    //configure the link to open in a separate window outside of the webapp
    return '<a href="'+url+'"'+title+' target="externalurl">'+disp+'</a>';
  }
  //run the link as javascript so it'll work in an iOS web app without launching Safari
  return '<a href="javascript:location.href=\''+url+'\';"'+title+'>'+disp+'</a>';
}

function Thumb (aUPC, aSort, aIdx, aQry, aX, aY, aZ, aM, aF, aD) {
  //draws the thumbnail image with a link to its specific title page
  document.write(Anchor(AnchorUrl(aUPC+'.php', aSort, aIdx, aQry, aX, aY, aZ, aM, aF, aD), Cover(aUPC, true, true), ''));
}
  
function fixIE(txt, url, title, external) {
  //IE doesn't allow for linked table cells so create a traditional hyperlink on the text for IE
  if (navigator.appName == 'Microsoft Internet Explorer' && url != '') {
    return Anchor(url, txt, title, external);
  } else {
    return txt;
  }
}

var urlPrev = '';
var urlNext = '';
function iButton(txt, imgl, w, tab, url, title, imgr, external) {
  var menustyle = (tab==1)?'menuFirst':(tab==2)?'menuJump':(tab==3)?'menuPrev':(tab==4)?'menuSelected':(tab==5)?'menuNext':(tab==6)?'menuJump':(tab==7)?'menuLast':'menuText';
  txt = '<span class="'+menustyle+'">' + txt + '</span>';
  txt = fixIE(txt, url, title, external);

  //draws a button with special edges and a filled middle
  dim = (tab == 4 ? 'd' : '');
  txt = '<td background='+_img+'bg'+dim+'.png valign=middle align=center width=100%>'+txt+'</td>';
  txt = '<td><img src="'+_img+imgl+'L'+dim+'.png" border=0></td>'+txt+'<td><img src="'+_img+(imgr?imgr:imgl)+'R'+dim+'.png" border=0></td>';
  txt = '<table border=0 cellpadding=0 cellspacing=0 width='+w+' height='+menuHeight+'><tr>'+txt+'</tr></table>';
  return (url != '') ? Anchor(url, txt, title, external) : txt;
}

function iCircle(txt, img, w, padl, padr, dim, url, title) {
  //draws a button with static middle and padded edges
  txt = fixIE(txt, url, title);
  txt = '<font color=#'+(dim ? 'AAAAAA' : 'FFFFFF')+' size=-1>'+txt+'</font>';
  dim = (dim ? 'd' : '');
  if (isDsk()) {
    //desktop browsers will squish the box so render it differently
    txt = '<td>'+space(w/4,menuHeight)+'</td><td valign=middle align=center width='+(w/2)+'>'+txt+'</td><td>'+space(w/4,menuHeight)+'</td>';
    txt = '<td><table border=0 cellpadding=0 cellspacing=0 background='+_img+img+dim+'.png><tr>'+txt+'</tr></table></td>';
  } else {
    txt = '<td background='+_img+img+dim+'.png valign=middle align=center width='+w+'>'+txt+'</td>';
  }
  txt = '<td>'+space(padl,1)+'</td>'+txt+'<td>'+space(padr,1)+'</td>';
  txt = '<table border=0 cellpadding=0 cellspacing=0 height='+menuHeight+'><tr>'+txt+'</tr></table>';
  return (url != '') ? Anchor(url, txt, title) : txt;
}

function gridAdjuster(row, increase, enabled) {
  if (row ) {
    if (enabled) {
      if (increase) {
        return '<span class="menuRowAdj">+</span>';
      }
      return '<span class="menuRowAdj">-</span>';
    }
    return '&nbsp;';
  }
  //column (hidden in iOS webapps)
  if (enabled) {
    if (increase) {
      return '<span class="menuColAdj">&gt;</span>';
    }
    return '<span class="menuColAdj">&lt;</span>';
  }
  return '&nbsp;';
  
}

function writeStats(aCount, aD, aH, aM, aTime) {
  //if this is a desktop browser or webapp in portrait mode, shows the stats at the bottom of the page
  //note that the php caller adds another restriction that webapp portrait must also be running the minimum row count
  if (isDsk() || isPortrait()) {
    document.write('<table border=0 cellpadding=0 cellspacing=0><tr>');
    if (isBig()) {
      document.write('<td><span class="statTitles">'+aCount+'&nbsp;titles</span> <span class="statHours">|&nbsp;'+aD+aH+aM+'</span> <span class="statUpdated">|&nbsp;updated&nbsp;'+aTime+'</span></td>');
    } else {
      document.write('<td><span class="statTitles">'+aCount+'&nbsp;titles</span> <span class="statHours">|&nbsp;'+aD+aH+aM+'</span><br><span class="statUpdated">updated&nbsp;'+aTime+'</span></td>');
    }
    document.write('</tr></table>');
  }
}

var _img = '_d_'; //this prefix is used to support more than one set of menu images (_d_ is desktop/etc, _p_ is webapp on iOS)
var _isApp = -1; //-1 means not initialized (see below for initialization)

function isApp () {
  if (_isApp < 0) {
    _isApp = 0; //0 represents desktop browser mode (or anything that isn't iPad, iPhone, or iPod - you can add new ones as 3+ to support your favored devices)
    if (navigator.standalone) { //standalone means this is running in webapp mode, i.e. launched from a homescreen icon, as opposed to Safari on iOS
      if (navigator.userAgent.indexOf("iPad") > 0) {
        _isApp = 1; //1 represents iPad in webapp mode
        _img = '_p_';
      } else if (navigator.userAgent.indexOf("iPhone") > 0 || navigator.userAgent.indexOf("iPod") > 0) {
        _isApp = 2; //2 represents iPhone/iPod in webapp mode
        _img = '_p_';
      }
    }
    calculateAppSizes();
  }
  
  //FOR ADVANCED USERS
  //you can add your own devices if you want, but ensure that 0 represents desktop, 1 is iPad, and 2 is iPhone/iPod
  //if you do add a new device, give it a new number >2, then be sure to categorize it properly in isBig (there is a php version of the function in utils.php)
  //also makes sure you initialize your new device's sizing settings in calculateAppSizes
  
  return _isApp;
}

function isBig() {
  //apps with decent real estate should consider themselves big

  return isApp() < 2;
}

function isDsk() {
  //apps that want to function the same as desktop (always include 0 for true desktop)
  return isApp() < 1;
}

function informAboutApp() {
  //this does a one time popup to tell Safari iOS users that they can add this to their home screen and run it as a web app
  var notified = GetCookie('appNotification');
  if (!notified && !navigator.standalone) {
    if (navigator.userAgent.indexOf("iPad") > 0 || navigator.userAgent.indexOf("iPhone") > 0 || navigator.userAgent.indexOf("iPod") > 0) {
      //browser has no record of previous notification, this is an iOS device, and it's not already running in app mode
      SetMyCookie('appNotification', 'previously prompted', "informAboutApp");
      alert("This website will run as an App on your iOS device if you add it to your home screen.");
    }
  }
}

//defaults are for desktop/android/etc browsers; calculateAppSizes sets these values for the iOS devices
var fullHeight = '';     //height of hi-res cover image when shown on a title's specific page (blank means to use image file's actual height) 
var fullWidth = '';      //width of hi-res cover image when shown on a title's specific page (blank means to use the image file's actual width)
var thumbHeight = '252'; //height of cover image thumbnails shown in the list of titles
var thumbWidth = '180';  //width of cover image thumbnails shown in the list of titles
var thumbPad = 2;        //number of empty pixels separating each of the thumbnail images in the list of titles
var thumbBorder = 0;     //number of empty pixels on the top, left, bottom, and right edges of the page in the list of titles
var thumbCols = 0;       //fixedcols values greater than zero indicate webapp mode to the php code, so desktop mode has to use zero
var thumbRows = 1;       //this determines how many rows there are by default and how many rows are added/removed when the +/- is clicked
var menuHeight = 30;     //height of the menu row/buttons (note: I have not tested if changing this value actually scales the menus nicely)
var menuBtnW = 76;       //width of normal menu buttons
var menuPadIn = 3;       //inner padding around the sizer buttons
var menuPadOut = 9;      //outer padding around the sizer buttons
var menuSortW = 128;     //width of the sort dropdown
var menuSearchWS = 128;  //width of search input box when shown on same line as menu (desktop or app in landscape)
var menuSearchWL = 640;  //width of search input box when show on its own line (app in portrait)

function isPortrait() {
  //true is portrait, false is landscape (only applicable on mobile devices)
  return (top.window.orientation == 0) || (top.window.orientation == 180);
}

function calculateAppSizes() {
  //iOS top status bar is 20px (retina automatically doubles everything so it actually doesn't need separate handling)
  //my menu bar is 30px per row (1 row landscape, 2 rows portrait)
  if (isApp() == 1) { //iPad

    menuHeight = 30;
    menuBtnW = 76;
    menuPadIn = 3;
    menuPadOut = 9;
    menuSortW = 128;
    menuSearchWS = 128;
    menuSearchWL = 640;
    if (isPortrait()) { //1004h 768w
        fullHeight = '959';
        fullWidth = '685';
        thumbHeight = '151';
        thumbWidth = '108';
        thumbPad = 1;
        thumbBorder = 2;
        thumbCols = 7;
        thumbRows = 6;
    } else { //748h 1024w
        fullHeight = '700';
        fullWidth = '500';
        thumbHeight = '238';
        thumbWidth = '170';
        thumbPad = 0;
        thumbBorder = 2;
        thumbCols = 6;
        thumbRows = 3;
    }
  } else if (isApp() == 2) { //iPhone, iPod

    menuHeight = 30;
    menuBtnW = 48;
    menuPadIn = 2;
    menuPadOut = 8;
    menuSortW = 69;
    menuSearchWS = 91;
    menuSearchWL = 251;
    if (isPortrait()) { //460h 320w
        fullHeight = '448';
        fullWidth = '320';
        thumbHeight = '90';
        thumbWidth = '64';
        thumbPad = 0;
        thumbBorder = 0;
        thumbCols = 5;
        thumbRows = 4;
    } else { //300h 480w
        fullHeight = '258';
        fullWidth = '184';
        thumbHeight = '135';
        thumbWidth = '96';
        thumbPad = 0;
        thumbBorder = 0;
        thumbCols = 5;
        thumbRows = 2;
    }
  } else {
  }
}

	var swiping = false;
	var swipe_fingers = 1;
	var swipe_x = 0;
	var swipe_y = 0;
	var swipe_direction = null;
	function touchCancel(event) {
		//reset the variables back to default values
		swiping = false;
		swipe_fingers = 0;
		swipe_x = 0;
		swipe_y = 0;
		swipe_direction = null;
	}
	
	function touchStart(event, fingers) {
		touchCancel(event);
		if ( event.touches.length == fingers ) {
			//store the starting coordinates
			swipe_fingers = fingers;
			for (var i = 0; i < swipe_fingers; i++) {
				swipe_x = swipe_x + event.touches[i].pageX;
				swipe_y = swipe_y + event.touches[i].pageY;
			}
			swipe_x = swipe_x / swipe_fingers;
			swipe_y = swipe_y / swipe_fingers;
			swiping = true;
		}
	}

	function touchMove(event) {
		if ( swiping && event.touches.length == swipe_fingers ) {
			var x = 0;
			var y = 0;
			for (var i = 0; i < swipe_fingers; i++) {
				x = x + event.touches[i].pageX;
				y = y + event.touches[i].pageY;
			}
			x = x / swipe_fingers;
			y = y / swipe_fingers;
			//lock in the direction if the swipe crosses or previously crossed the distance threshold
			if ( swipe_direction || isSwipe(x,y) ) {
				calculateDirection(x,y);
				if (swipe_direction == 'left' || swipe_direction == 'right') {
					event.preventDefault(); //don't do up/down motions if he's swiping left/right
				} else {
					touchCancel(event); //abort swipe once he's tried going up/down
				}
			}
		} else {
			touchCancel(event);
		}
	}
	
	function touchEnd(event) {
		if ( swiping && swipe_direction ) {
			event.preventDefault();
			var newUrl = getSwipeUrl();
			if (newUrl != '') {
				location.href = newUrl;
			}
		}	
		touchCancel(event);
	}

	function isSwipe(curX, curY) {
		var swipeLength = Math.round(Math.sqrt(Math.pow(curX - swipe_x, 2) + Math.pow(curY - swipe_y, 2)));
		return swipeLength >= 72;
	}

	function calculateDirection(curX, curY) {
		var X = swipe_x-curX;
		var Y = curY-swipe_y;
		var Z = Math.round(Math.sqrt(Math.pow(X,2)+Math.pow(Y,2))); //the distance - rounded - in pixels
		var r = Math.atan2(Y,X); //angle in radians (Cartesian system)
		var a = Math.round(r*180/Math.PI); //angle in degrees
		if ( a < 0 ) {
			a = 360 - Math.abs(a);
		}
		if ( (a <= 30) && (a >= 0) ) {
			swipe_direction = 'left';
		} else if ( (a <= 360) && (a >= 330) ) {
			swipe_direction = 'left';
		} else if ( (a >= 150) && (a <= 210) ) {
			swipe_direction = 'right';
		} else if ( (a > 60) && (a < 120) ) {
			swipe_direction = 'down';
		} else if ( (a > 240) && (a < 300) ) {
			swipe_direction = 'up';
		} else {
			swipe_direction = 'diagonal';
		}
	}
	
	function getSwipeUrl() {
		if ( swipe_direction == 'left' ) {
			return urlNext;
		} else if ( swipe_direction == 'right' ) {
			return urlPrev;
		} else if ( swipe_direction == 'up' ) {
		} else if ( swipe_direction == 'down' ) {
		}
		return '';
	}



