
$(document).ready(function(){
var
hy = countJs = 0,
goBF = false,
ha = bcs = [],
hE = $('<div class="fbDialog" role="alert"></div>'),
pL = $('<div class="fbDialog" role="alert"></div>'),
plS = '<span class="screenReading">Loading, please wait.</span>',
plI = '<img width="36" height="50" src="/images/sand_clock_indigo.png" alt="" />',
fs = '<span class="forceShow"></span>',
prevURL = '',
currentURL = location.href;

// Browse
var bm = $('<div class="dialog bmDialog"><div class="screenReading">Menu Start<span class="forceShow"></span></div><div><h2 tabindex="-1">Browse Categories</h2></div><a class="closeLnk" href="#"><img class="closeImg" src="/extra/images/close.gif" alt="Close" title="Close" /></a><div id="browseMenuIndex"></div><div class="screenReading"><a class="closeLnk" href="#">Close</a>Menu End<span class="forceShow"></span></div></div>');
$('#browseLnk').click(function(ev){
if ($('#browseLnk').data('open')) return false;
$('#browseLnk').data('open', true);
$('.dialog').remove();
if ($('#devLnk').data('open')) $('#devLnk').data('open', false);
bm.css({
top: $('#pch').offset().top + $('#pch').height() + 'px',
left: $('div.hd').first().offset().left + 'px'
});
$(this).after(bm);
bm.find('#browseMenuIndex').html($('#browseMenu').html()).end().find('.closeLnk').click(function(ev){
bm.remove();
$('.forceShow').html('');
$('#browseLnk').data('open', false).focus();
ev.preventDefault();
}).end().find('.awsHref').click(function(ev){
parse(this.href);
ev.preventDefault();
});
$('.forceShow').html('&nbsp;');
bm.find('h2').focus();
ev.preventDefault();
});

// Copy
$('#copyLnk').click(function(ev){
var arr = currentURL.split('?');
arr[0] = 'http://gutterstar.net/amazon.php';
var text2copy = arr.join('?');
if (window.clipboardData){
window.clipboardData.setData("Text", text2copy);
} else {
var c = $('<div class="dialog sDialog"><label for="cLink">Item link:</label><br /><textarea rows="1" cols="50" id="cLink">' + text2copy + '</textarea></div>');
$(this).after(c);
$('#cLink').focus().select().blur(function(ev){
c.remove();
});
}
ev.preventDefault();
});

// Add to favorites
$('#addLnk').click(function(ev){
var
arr = currentURL.split('?'),
subject = $('#pch').data('subject');
arr[0] = 'http://gutterstar.net/amazon.php';
var url = arr.join('?');
if (!subject) var title = 'Amazon Recommends ';
else var title = subject;
title = title.replace(/&#(\d+);/g, '');
title = title.replace(/\\|\-|\.|\~|\,|\/|\!|\@|\#|\$|\^|\&|\*|\(|\)|\_|\%5C|\%7E|\%2C|\%2F|\%21|\%40|\%23|\%24|\%25|\%5E|\%26|\%2A|\%28|\%29|\+|\||\`|\?|\:|\;|\%2B|\%7C|\%60|\%3F|\%3A|\%3B|\=|\%3D|\%27|\%22|\%2E/g, '');
if (window.sidebar) window.sidebar.addPanel(title, url, "");
else if (window.opera && window.print) $('<a></a>').attr('href', url).attr('title', title).attr('rel', 'sidebar').click();
else if (document.all) window.external.AddFavorite(url, title);
ev.preventDefault();
});

// Email
var sef = $('<div class="dialog sDialog"><div class="screenReading">Email Start<span class="forceShow"></span></div><div><h2 tabindex="-1">Send Item Info</h2></div><a class="closeLnk" href="#"><img class="closeImg" src="/extra/images/close.gif" alt="Close" title="Close" /></a><br /><div tabindex="-1" id="recResultJs"></div><form><div><label for="yNameJs">Your name:</label><input type="text" id="yNameJs" name="yName" maxlength="100" /></div><div><label for="yEmailJs">Your email:</label><input type="text" id="yEmailJs" name="yEmail" maxlength="100" /></div><div><label for="fNameJs">Recipient\'s name:</label><input type="text" id="fNameJs" name="fName" maxlength="100" /></div><div><label for="fEmailJs"><span class="rfn">Recipient</span>\'s email:</label><input type="text" id="fEmailJs" name="fEmail" maxlength="100" /></div><div><label for="msgJs">Message to <span class="rfn">recipient</span>:</label><br /><textarea id="msgJs" name="msg" rows="3" cols="40" maxlength="300"></textarea></div><div><input type="submit" name="submit" value="Send..." /></div></form><div class="screenReading"><a class="closeLnk" href="#">Close</a>Email End<span class="forceShow"></span></div></div>');

$('#emailLnk').click(function(ev){
if ($(this).data('open')) return false;
$(this).data('open', true);
$('.dialog').remove();
if ($('#devLnk').data('open')) $('#devLnk').data('open', false);
$(this).after(sef);
var ua = currentURL.split('?');
ua[0] = 'http://gutterstar.net/amazon.php';
var url = ua.join('?');
sef.find('form').append('<input type="hidden" name="href" value="' + url + '" />').submit(function(ev){
var error = false;
$.each(this.elements, function(){
if (!this.value) error = true;
});
if (error)
$('#recResultJs').html('<div class="error">Error: All fields are required.</div>').focus();
else {
var d = new Date();
var u = 'ajax/recommend_send.php?' + $(this).serialize() + '&pTitle=' + encodeURIComponent('Amazon Search - ' + $('#pch').data('subject')) + '&ts=' + d.getTime();
$('#recResultJs').html('<div style="color: #800000;">Please wait.</div>').load(u, function(responseText, responseStatus, xmlHttpRequest){
$('#fNameJs, #fEmailJs, #msgJs').val('');
$('#recResultJs').focus();
});
}
ev.preventDefault();
}).find('#fNameJs').blur(function(){
$('span.rfn').text($(this).val());
}).end().end().find('.closeLnk').click(function(ev){
sef.remove();
$('.forceShow').html('');
$('#emailLnk').data('open', false).focus();
ev.preventDefault();
});
$('.forceShow').html('&nbsp;');
$(sef).find('#yNameJs').focus();
ev.preventDefault();
});

// Go back
$('#backLnk').click(function(ev){
goBack();
ev.preventDefault();
});

function goBack(){
if (hy>0){
goBF = true;
ha[hy] = currentURL;
hy = hy-1;
parse(ha[hy]);
} else historyEmpty();
}

// Go forward
$('#nextLnk').click(function(ev){
goForward();
ev.preventDefault();
});

function goForward(){
if (ha[hy+1]){
goBF = true;
parse(ha[hy+1]);
hy++;
} else historyEmpty();
}

function historyEmpty(){
$('fbDialog').remove();
$('body').append(hE);
hE.html('<span>Page not found.</span>');
tempTimer = setTimeout(function (){
hE.remove();
}, 2000);
}

// Dev Form
function fetchDev(sMethod, sUrlBase, sUrlArguments, bIsAsync, sBody){
$.ajax({
method: "get",
url: sUrlBase,
beforeSend: function(){
$('#jsExample').html('<span>Loading...</span>');
},
success: function(html){
$('#jsExample').html(html);
}
});
}

var df = $('<div class="dialog dfsDialog tal"></div>');
$('#devLnk').click(function(ev){
if ($('#devLnk').data('open')) return false;
$('#devLnk').data('open', true).css('cursor', 'wait');
$('.dialog').remove();
df.load('/extra/awsDevForm.php', function(responseText, textStatus, XMLHttpRequest){
$('form#searchForm').after(df);
df.find('.closeLnk').click(function(ev){
df.remove();
$('#devLnk').data('open', false).focus();
ev.preventDefault();
}).end().find('form').submit(function(ev){
var u = 'amazon.php?' + $(this).serialize();
var c = $('<textarea title="Code to insert into your webpage..." rows="3" cols="50" id="codeText"><' + 'script type="text/javascript" src="http://gutterstar.net/' + u + '"></' + 'script' + '></textarea>');
$('#jsCode').html(c);
var jsE = $('#jsExample');
c.focus().select();
fetchDev('GET', 'cgi-bin/booksearch/import.php?countJs=' + countJs + '&url=' + encodeURIComponent($(this).serialize()), '', true, '');
countJs++;
ev.preventDefault();
}).find('.checkIncludes').each(function(){
$(this).change(function(ev){
if ($('#jsInclude1').val() == 'no' && $('#jsInclude2').val() == 'no'){
if ($(this).attr('id') == 'jsInclude1')
$('select#jsInclude2 > option').first().attr('selected', 'selected');
else if ($(this).attr('id') == 'jsInclude2')
$('select#jsInclude1 > option').first().attr('selected', 'selected');
}
$('.checkDisabled').trigger('checkDisabled');
});
}).end().find('.checkDisabled').each(function(){
$(this).bind('checkDisabled', function(ev){
var e = $('#jsInclude1');
var i1 = $('#jsImgS');
var i2 = $('#jsImgA');
var t = $('#jsIncludeDesc');
var t1 = $('#jsTA');
if ($(e).val() == 'yes'){
$(i1).attr('disabled', false);
$(i2).attr('disabled', false);
} else {
$(i1).attr('disabled', 'disabled');
$(i2).attr('disabled', 'disabled');
}
if ($(t).val() == 'yes') $(t1).attr('disabled', false);
else $(t1).attr('disabled', 'disabled');
}).change(function(ev){
$(this).trigger('checkDisabled');
});
});
$('.forceShow').html('&nbsp;');
df.find('h2').focus();
$('#devLnk').css('cursor', 'pointer');
});
ev.preventDefault();
});

// content fetcher
function fetch(sMethod, sUrlBase, sUrlArguments, bIsAsync, sBody){
if ($('#pageContent').data('loading')) return false;
$('#pageContent').data('loading', true);
$('.dialog').remove();
if ($('#devLnk').data('open')) $('#devLnk').data('open', false);
if ($('#bcLnk').data('open')) $('#bcLnk').trigger('click');
var u = sUrlBase,
vrArr = urlVars = null;
if (sUrlArguments){
vrArr = sUrlArguments.split('&');
$.each(vrArr, function(i, v){
urlVars = v.split('=');
urlVars[1] = encodeURIComponent(urlVars[1]);
v = urlVars.join('=');
});
sUrlArguments = vrArr.join('&');
u = 'cgi-bin/booksearch/amazon_products_feed.cgi?' + sUrlArguments;
}
prevURL = currentURL;
currentURL = u;
updateBCs();
sUrlArguments = u.split('?');
vrArr = sUrlArguments[1].split('&');
$.each(vrArr, function(i, v){
urlVars = v.split('=');
if (urlVars[0] == 'go' && urlVars[1] == 'amazon'){
$(window.open(u, 'amznwin', 'location=yes,scrollbars=yes,status=yes,toolbar=yes,resizable=yes')).focus();
return false;
}
if (urlVars[0] != 'Sort' && urlVars[0] != 'locale' && urlVars[0] != 'SearchIndex' && urlVars[0] != 'BrowseNode'){
urlVars[1] = urlVars[1].replace(/\\|\-|\.|\~|\,|\/|\!|\@|\#|\$|\^|\&|\*|\(|\)|\_|\%5C|\%7E|\%2C|\%2F|\%21|\%40|\%23|\%24|\%25|\%5E|\%26|\%2A|\%28|\%29|\+|\||\`|\?|\:|\;|\%2B|\%7C|\%60|\%3F|\%3A|\%3B|\=|\%3D|\%27|\%22|\%2E/g, '%20');
urlVars[1] = urlVars[1].replace(/\%20\%20/g, '%20');
}
v = urlVars.join('=');
});
sUrlArguments[0] = 'cgi-bin/booksearch/amazon_products_feed.cgi';
sUrlArguments[1] = vrArr.join('&');
u = sUrlArguments.join('?');
$.ajax({
method: "get",
url: u,
beforeSend: function(){
if (!goBF){
if (prevURL && prevURL != location.href){
ha[hy] = prevURL;
hy++;
}
} else goBF = false;
$('fbDialog').remove();
$('body').append(pL);
pL.html(plI).append(plS);
$.cookies.set('prevURL', prevURL, {hoursToLive: 24*360});
$.cookies.set('currentURL', currentURL, {hoursToLive: 24*360});
},
success: function(html){
pL.remove();
$('#pageContent').empty().html(html).prepend(fs).append(fs).find('.forceShow').addClass('screenReading').html('&nbsp;').end()
.find('.awsHref').click(function(ev){
parse(this.href);
ev.preventDefault();
}).end().find('.awsForm').submit(function(ev){
parseForm(this);
ev.preventDefault();
}).end().find('.goBack').click(function(ev){
goBack();
ev.preventDefault();
}).end().find('a.showHiddenScript1, a.showHiddenScript2, a.showHiddenScript3').click(function(ev){
$(this).addClass('hidden');
if ($(this).hasClass('showHiddenScript1'))
$(this).parent().parent().find('div.showHiddenScript1').removeClass('hidden');
else if ($(this).hasClass('showHiddenScript2'))
$(this).parent().parent().find('div.showHiddenScript2').removeClass('hidden');
else if ($(this).hasClass('showHiddenScript3'))
$(this).parent().parent().find('div.showHiddenScript3').removeClass('hidden');
ev.preventDefault();
});
$('#pch').data('subject', $('#pchs').text()).attr('tabindex', '-1');
if (!$('#pageContent').data('fLoad')) $('#pch').focus();
else $('#pageContent').data('fLoad', false);
$('#pageContent').data('loading', false);
},
complete: function(){
$.cookies.set('bcs', bcs, {hoursToLive: 24*360});
}
});
}

// parse href
function parse(url){
fetch('GET', url, '', true, '');
}

$('.awsHref').bind('click', function(ev){
parse($(this).attr('href'));
ev.preventDefault();
});

// parse form
function parseForm(form){
fetch('GET', 'http://gutterstar.net/cgi-bin/booksearch/amazon_products_feed.cgi?' + $(form).serialize(), '', true, '');
}

$('.awsForm').bind('submit', function(ev){
parseForm($(this));
ev.preventDefault();
});

// Breadcrumbs
var bc = $('<div class="bcLnks"></div>'),
bcs = [];
$('#bcLnk').click(function(ev){
if ($(this).data('open')) {
$(this).data('open', false).attr('title', 'Open breadcrumb history').find('small').first().html('&#9660;');
bc.remove();
} else {
$(this).data('open', true).attr('title', 'Close breadcrumb history').find('small').first().html('&#9650;');
$('div.breadcrumbs').first().append(bc);
showBCs();
}
ev.preventDefault();
});

function updateBCs(){
var
subject = $('#pch').data('subject'),
found = false,
bcA = [ ];
if (prevURL && subject && prevURL != location.href){
bcA = [prevURL, subject];
$.each(bcs, function(i, v){
if (v[1] == bcA[1]){
v = bcA;
found = true;
}
});
if (!found)
bcs.push(bcA);
if (bcs.length > 10)
bcs.shift();
}
}

var bcul = $('<ul class="menuList"></ul>');
function showBCs(){
if (!bcs.length || !$('#bcLnk').data('open')) return false;
bcul.empty();
$.each(bcs, function(i, v){
bcul.append('<li><a class="awsHrefLnk" href="' + v[0] + '"><small>&#9654;</small> ' + v[1] + '</a></li>');
});
bc.html(bcul);
bcul.find('a').click(function(ev){
var u = this.href;
$('#bcLnk').trigger('click');
parse(u);
ev.preventDefault();
});
}

$('#pageContent').data('fLoad', true);

if (!location.href.split('?')[1]){
if ($.cookies.get('bcs')) bcs = $.cookies.get('bcs');
if ($.cookies.get('prevURL')) prevURL = $.cookies.get('prevURL');
if ($.cookies.get('currentURL')) currentURL = $.cookies.get('currentURL');
}

if (prevURL && currentURL.split('?')[1] && bcs.length)
parse(currentURL);
else
parseForm($('#searchForm'));
});
