
function customCSS() {
   // Don't rely on this for any security checks! Display convenience only
   var isUser = document.cookie.indexOf('EL::AuthCookieHandler_ELRealm');
   var isAdmin = document.cookie.indexOf('user_is_admin');

   if (isUser < 0) {
     document.write('<link href="/etc/anon.css" rel="stylesheet" type="text/css" />');
     return;
   }
   if (isUser >= 0 && isAdmin >= 0) {
     document.write('<link href="/etc/admin.css" rel="stylesheet" type="text/css" />');
     return;
   }   
   if (isUser >= 0 && isAdmin < 0) {
     document.write('<link href="/etc/user.css" rel="stylesheet" type="text/css" />');
     return;
   }
}

customCSS();


// STOLEN COOKIE CODE FROM WEBREFERENCE.COM
// name - name of the cookie
// value - value of the cookie
// [expires] - expiration date of the cookie (defaults to end of current session)
// [path] - path for which the cookie is valid (defaults to path of calling document)
// [domain] - domain for which the cookie is valid (defaults to domain of calling document)
// [secure] - Boolean value indicating if the cookie transmission requires a secure transmission
// * an argument defaults when it is assigned null as a placeholder
// * a null placeholder is not required for trailing omitted arguments
function setCookie(name, value, expires, path, domain, secure) {
  var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
}

// name - name of the desired cookie
// * return string containing value of specified cookie or null if cookie does not exist
function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}

// name - name of the cookie
// [path] - path of the cookie (must be same as path used to create cookie)
// [domain] - domain of the cookie (must be same as domain used to create cookie)
// * path and domain default if assigned null or omitted if no explicit argument proceeds
function deleteCookie(name, path, domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" + 
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

// date - any instance of the Date object
// * hand all instances of the Date object to this function for "repairs"
function fixDate(date) {
  var base = new Date(0);
  var skew = base.getTime();
  if (skew > 0)
    date.setTime(date.getTime() - skew);
}

// END OF STOLEN COOKIE FUNCTIONS

var rvb_row_sep = ';;';
var rvb_col_sep = '::';
// rvb means recently viewed books
var rvb_max = 8;  // number of books to show
//var rvb_template = '<div class="rvb"><a href="/book/ISBN" class="rvbTitle">TITLE</a><br /><div align="right" style="margin-top:4px"><span class="rvbPrice">PRICE_KRW </span><span class="cartButton" style="border-right-style:none"><a class="cartButton" href="/cart?add=ISBN"><img src="/img/icon/cart_white.gif" width="20" height="10" alt="cart" border="0" />ADD</a></span></div></div>';
var rvb_template = '<div class="rvb"><a href="/book/ISBN" class="rvbTitle">TITLE</a><br /><div align="right" style="margin-top:4px"><span class="rvbPrice">PRICE_KRW </span></div></div>';


function add_rvb(rvb_data) {
  var rvb_ary = get_rvb_ary();
  rvb_ary.unshift(rvb_data.join(rvb_col_sep));
  if (rvb_ary.length > rvb_max) rvb_ary.length = rvb_max;
  put_rvb_ary(rvb_ary);
  return;
}

function get_rvb_ary() {
  var rvb_cookieval = getCookie('rvb');
  if (!rvb_cookieval) {
//    alert("no cookie? "+document.cookie);
    return new Array();
  }
  var rvb_ary = rvb_cookieval.split(rvb_row_sep);
  return rvb_ary;
}

function put_rvb_ary(rvb_ary) {
  var expires = new Date('2200',0,1);
  setCookie('rvb',rvb_ary.join(rvb_row_sep), expires, "/");
  return;
}


function get_session_ary() {
  var ses_cookieval = getCookie('EL::AuthCookieHandler_ELRealm');
  if (!ses_cookieval) {
    return new Array();
  }
  var session_ary = ses_cookieval.split('*');
  return session_ary;
}

function interpolate(keys, template) {
  var result = template;
  for (var key in keys) {
    var re = new RegExp(key, "gm");
    result = result.replace(re, keys[key]);
  }
  return result;
}

var session_ary = get_session_ary();    
var username = session_ary[1];
var current_img;

//// Looking for COVER_ISBN? it's in the header template file

function bookCovers(booksInfo){
  for (var i in booksInfo) { 
     var book = booksInfo[i]; 
     var bibkey = book.bib_key;
     if (bibkey == null) continue;
     var match_ary = bibkey.match(/ISBN\:?(\w+)/);
     var isbn = (match_ary==null)? null : match_ary[1];
     if (isbn == null) continue;

     var preview_avail  = book.preview; // full, partial, or noview
     var src = book.thumbnail_url;

     if (src != null) {
	 src = src.replace(/&edge=curl/i, "");
	 src = src.replace(/zoom=5/i, "zoom=1");
	 //	 var img = document.createElement("img");
	 var img = new Image();

 	 img.onload = img_onload_closure(isbn,src,img);
	 img.src = src;

     } 
  }
}
function img_onload_closure(isbn,src,img) {
    
   return function() {
	     replaceCover(isbn, src, "t", Math.round(img.width*.3), Math.round(img.height*.3));
	     replaceCover(isbn, src, "s", Math.round(img.width*.5), Math.round(img.height*.5));
	     replaceCover(isbn, src, "m", img.width, img.height);
         };
}
function replaceCover(isbn,src,size,width,height) {
    //        alert("replacing"+isbn+";"+size);
    $(".bookCover-"+isbn+"-"+size).attr("width", width).attr("height", height).attr("src", src);
}


$(document).ready(function() {
  $("input.button").button();
 
  $(".cart-item-status").each(function(index) {
	 var id = $(this).attr("id");
	 var matches = id.match( /cart-item-status-(.+)/ );
	 if (matches == null) return;
	 var isbn = matches[1];
	 cart_item_status(isbn);
     });
 // $(".wishlist-item-remove").button();
  $("button").button();

  $("#global-search-input").autocomplete({source: "/ajax/search_autocomplete", html: true, minLength: 4, delay: 200, 
	      select: function(event, ui) { $("#global-search-input").val(ui.item.value); $("#global-search-form").submit();},
	      focus: function(event, ui) {  return false; }
      });


});


function cart_item_status(isbn) {
    $("#cart-item-status-"+isbn).load("/ajax/cart_item_status", {isbn: isbn});
}

function cart_item_add(isbn,qty) {

   $.get("/ajax/cart_item_add", {isbn: isbn, qty: qty}, function(ret) {
	   ret = JSON.parse(ret);
	   if (ret.error != 0) {
	       alert("Error: "+ret.error);
	   } else {
	       cart_item_status(isbn);
	   }
       });

   return false;   
}

function wishlist_item_remove(isbn) {
    $("#wishlist-item-"+isbn).fadeOut(1500);
    $.get("/ajax/wishlist_item_remove", {isbn: isbn});
}

function wishlist_item_move(isbn,dir) {
    document.location.href = "/customer/wishlist/move/"+isbn+"/"+dir;
}

$("button").button();

function admin_add_item_lookup() {
    var isbn = $("#isbn").val();
    if (isbn.length != 13) return alert("ISBN 13 only");

    //    isbn = "9780812981940";
    //    console.log(isbn);
    $.getScript("https://www.googleapis.com/books/v1/volumes?q=isbn:"+isbn+"&callback=admin_add_item_handler");
    return false;
}

function admin_add_item_handler(data) {
    if (data==null) return;
    var items = data.items;
    if (items==null) return;
    var info = items[0].volumeInfo;
    if (info==null || info.title==null) return;
    var title = info.title;
    //    title.replace(/
    
    var title_escaped = encodeURI('"' + title + '"');

    $.getScript("https://www.googleapis.com/books/v1/volumes?q=intitle:"+title_escaped+"&callback=admin_add_item_title_handler");    

}


function admin_add_item_title_handler(data) {
    $("#items").empty();
    if (data==null) return;
    var items = data.items;
    if (items==null) return;
    var first;
    for (var i = 0; i < items.length; i++) {
	var info = items[i].volumeInfo;
	if (info==null) continue;
	var title = info.title;
	if (title==null) continue;
	if (info.industryIdentifiers[1]==null) continue;
	var isbn = info.industryIdentifiers[1].identifier;
	if (isbn==null) continue;

	// Skip the ISBN-13 that is in the ISBN form field
	if (isbn == $("#isbn").val()) {
	    continue;
	}

	if (first==null) {
	    admin_add_item_choose(isbn);
	    first = i;
	}
	var row = "";
	row += "<div>";
	row += "<a href='javascript:void(admin_add_item_choose(\""+ isbn + "\"))'>";
	if (info.imageLinks!=null && info.imageLinks.thumbnail!=null) {
	    row += "<img src='"+info.imageLinks.thumbnail+ "' /> &nbsp; ";
	} else {
	    row += "<img src='/img/cleardot.gif' width='130' /> &nbsp; ";
	}

	row += isbn + "</a>" + ": &nbsp; ";
	row += title;
	row += "</div>";
	$("#items").append(row);
	
    }
}

function admin_add_item_choose(isbn) {
    $("#copy_isbn").val(isbn);
}


function gc_get_balance(form_el) {
    var cardid = form_el.cardid.value;
    var pin = form_el.pin.value;
    $("#gc_balance").load("/ajax/gc_get_balance", {cardid: cardid, pin: pin});    
}

function gc_add(form_el) {
    var cardid = form_el.cardid.value;
    var pin = form_el.pin.value;
    var amount = form_el.amount.value;
    $("#gc_balance").text("Loading...");
    
    $.post("/ajax/gc_add", {cardid: cardid, pin: pin, amount: amount}, function(ret) {
	    ret = JSON.parse(ret);
	    $("#gc_balance").text("");
	    if (ret.error) {
		$("#gc_success").hide();
		$("#gc_error").html(ret.error).show();
	    } else {
		if (ret.success) {
		    $("#gc_error").hide();
		    $("#gc_success").html(ret.success).show();
		    gc_load_list();
		}
	    }
	    form_el.cardid.value = "";
	    form_el.pin.value = "";
	    form_el.amount.value = "";
	    
	});

}
function gc_remove(cardid) {
    //    $("#gc_balance").text("Loading...");

    //    if (!confirm("Remove this Gift Card?")) return;

    $("#gc_list").html('<img src="/img/ajax-loader-bar.gif" />');

    $.post("/ajax/gc_remove", {cardid: cardid}, function(ret) {
	    if (ret.error) alert(ret.error);
	    gc_load_list();
	});

}

function gc_cc_add(form_el,uid) {
    var amount = form_el.gc_cc_amount.value;
    var cardid = 'USER_' + uid;
    $("#gc_list").html('<img src="/img/ajax-loader-bar.gif" />');

    $.post("/ajax/gc_add", {cardid: cardid, amount: amount}, function(ret) {
	    ret = JSON.parse(ret);

	    if (ret.error) {
		$("#gc_cc_success").hide();
		$("#gc_cc_error").html(ret.error).fadeIn();
	    } else {
		if (ret.success) {
		    $("#gc_cc_error").hide();
		    $("#gc_cc_success").html(ret.success).fadeIn();
		    gc_load_list();
		}
	    }
	    form_el.gc_cc_amount.value = "";
	    
	});

}

function gc_load_list() {
    $.get("/ajax/gc_load_list", {}, function(ret) {
	    ret = JSON.parse(ret);
	    if (ret.error) {
		return alert(ret.error);
	    }
	    $("#gc_amount_due").html(ret.order_amount_due);
	    $("#gc_list").empty();
	    var using_cc = false;

	    if (ret.rows && ret.rows.length) {
		$("#gc_list").show();
		for (var i = 0; i < ret.rows.length; i++) {
		    var row = ret.rows[i];
		    var label;
		    if (row.cardid.match(/USER/)) {
			label = "Customer Credit";
			using_cc = true;


		    } else {
			label = "Gift Card (Number "+row.cardid+")";
		    }
		    var remove_button = ' &nbsp; <a href="#" onclick="gc_remove(\'' +row.cardid+ '\');return false"><span class="ui-icon ui-icon-trash" style="display:inline-block"></span></a>';
		    $("#gc_list").append("<div>Applied " + label + ": " + row.amount_formatted + remove_button + "</div");
		    

			
		}
	    }
	    if (using_cc) {
		$("#gc_cc_container").fadeOut(2000);
		$("#gc_cc_error").fadeIn(2000);
		$("#gc_cc_success").fadeIn(2000)
	    } else {
		$("#gc_cc_error").text("");
		$("#gc_cc_success").text("");

		$("#gc_cc_container").fadeIn();
	    }
	    
	});

}

function gc_cc_refresh() {

}
var going_back;
function checkout_back(action) {
    //alert(action);
    going_back = true;
    if (!action) {
	window.location = "/cart";

	return false;
    }
    window.location = "/checkout?next_action=" + action;
    return false;
    $("input[name=next_action]").val(action);
    $("input[name=next_action]").closest("form").submit();

    return false;
}
