var askitWindow;
function goAskIt() {
    if (!askitWindow || askitWindow.closed) {
        askitWindow = window.open('http://admin.askit.com/ai/askit.taf?topic=218140', 'askit', 'toolbar=no,location=no,directories=no,status=no,menubar=yes,scrollbars=yes,resizable=yes,width=650,height=550');
    } else {
        askitWindow.focus();
        askitWindow.location = 'http://admin.askit.com/ai/askit.taf?topic=218140';
    }
}

var text;
function hideQuery(obj) {
    if (!obj) obj = document.forms['productSearch'].elements['query'];
    if (!obj) return false;
    if ((obj.value.indexOf('Title') != -1 &&
        obj.value.indexOf('Author') != -1 &&
        obj.value.indexOf('Keyword') != -1)
        ||
        (obj.value.indexOf('Email') != -1 &&
            obj.value.indexOf('Address') != -1)
        ||
        (obj.value.indexOf('Enter') != -1 &&
            obj.value.indexOf('ISBN') != -1)) {
        text = obj.value;
    }
    if (obj.value == text) obj.value = '';

    obj.onfocus = function () {
        if (obj.value == text) obj.value = '';
    }
    obj.onblur = function () {
        if (obj.value == '') obj.value = text;
    }
    return obj.focus();
}

var currentTab = 'buy';
function setFormMode(tab) {
    var sell = document.getElementById('tab-sell');
    var buy = document.getElementById('tab-buy');

    var bsell = document.getElementById('button-sell');
    var bbuy = document.getElementById('button-buy');

    var lfind = document.getElementById('find-on-us');
    var f = document.getElementById('form-isbn');
    var q = document.getElementById('query');


    currentTab = tab;
    if (tab == 'buy') {
        sell.style.display = 'none';
        bsell.style.display = 'none';

        buy.style.display = 'block';
        bbuy.style.display = 'block';

        lfind.innerHTML = 'Find your books on textbookx.com';
        q.name = 'query';
        f.action = '/fastsearch2.php';
        q.value = q.title = 'Enter ISBN, Title, Author or Keyword';
    } else {
        sell.style.display = 'block';
        bsell.style.display = 'block';

        buy.style.display = 'none';
        bbuy.style.display = 'none';

        lfind.innerHTML = 'Sell your books on textbookx.com';
        q.name = 'isbn';
        f.action = '/account/post.php';
        q.value = q.title = 'Enter the ISBN of the item you wish to sell';
    }
    return false;
}

function submitSellForm(f) {
    if (currentTab == 'sell') {
        n = f.query == undefined ? document.getElementById('query').value : f.query.value;
        addn = n.toLowerCase().indexOf('x') > 8 ? 1 : 0;
        n = n.replace(/\D*/gi, '');
        if (isNaN(parseFloat(n)) || (n.length != 13 && (n.length + addn) != 10)) {
            document.getElementById('correctisbn').style.visibility = 'visible';
            return false;
        } else return true;
    }
}

function hideISBNError() {
    document.getElementById('correctisbn').style.visibility = 'hidden';
}

function checkFaculty(f) {
    var form = (f ? f : document.forms['frmLogin']);
    if (!form) return false;
    var facultyBox = form.elements['isFaculty'];
    if (!facultyBox) return false;
    if (facultyBox.checked) {
        form.action = '/institutional/staff.php';
    } else {
        form.action = form.elements['sslUrl'].value + 'account/login.php';
    }
    return true;
}

function popIt(obj) {
    popupWin = window.open(obj.href, 'isbnwindow', 'width=300,height=300,scrollbars=yes,toolbar=no,menubar=no');
    popupWin.focus();
}

function doInputFocus(inp, isFocused) {
    if (isFocused === true) {
        $(inp).parent().parent().addClass('input-active').removeClass('input-red');
    } else {
        $(inp).parent().parent().removeClass('input-active');
    }
}
var infobox_target = null;
function infobox(boxOptions) {
    var infoBox = boxOptions.isError === true ? $('#checkout-errorbox') : $('#checkout-infobox');

    if (boxOptions.show === false) {
        if (infoBox.is(':visible')) infoBox.css('opacity', '1').hide().animate({opacity:0}, 400);
        if (infobox_target != null) infobox_target.focus();
        return false;
    }

    $('.ci-text', infoBox).html(boxOptions.text);

    var target = boxOptions.target ? $('#' + boxOptions.target + ':visible') : $('.checkout-button-next:visible').first();
    if (!target || typeof target === 'undefined') target = $('.checkout-button-next:visible').first();
    infobox_target = target;

    if (!target.length) return false;
    var targetwidth = Math.min(target.width(), 400);

    if (targetwidth > 220) {
        infoBox.css('width', targetwidth + 23);
    } else {
        infoBox.css('width', 280);
    }
    infoBox.css({
        'left':parseInt(target.offset().left, 10) + targetwidth - infoBox.width() + 12 + 'px',
        'top':parseInt(target.offset().top, 10) - infoBox.height() + 2 + 'px'
    });
    infoBox.css('opacity', '0').show().animate({opacity:1}, 400, "linear", function () {
        infoBox.css('opacity', '');
    });

    if (boxOptions.isError) target.focus();
    if (boxOptions.isError && (target.is(':text') || target.is(':password'))) {
        target.parent().parent().addClass('input-red');
        target.one('keypress', function () {
            target.parent().parent().removeClass('input-red');
            infoboxHide();
        });
    } else if (target.parent().parent().hasClass('dropdown-with-hightlight')) {
        target.parent().parent().one('click', function () {
            infoboxHide();
        });
    }
    return false;
}

function infoboxError(text, target) {
    return infobox({text:text, target:target, isError:true, show:true});
}
function infoboxNotice(text, target) {
    return infobox({text:text, target:target, isError:false, show:true});
}
function infoboxHide() {
    infobox({isError:false, show:false});
    return infobox({isError:true, show:false});
}

var emailRequestSent = null;

function sendUsernameResponse(uname, subm) {
    $.ajax({
        url:'/tools/ajax/misc_ajax.php?action=searchUser&uname=' + uname,
        type:"POST",
        dataType:"json",
        error:function (xhr, ajaxOptions, thrownError) {
            infoboxError('Action failed. Please try again.', '');
        },
        success:function (resp) {
            if (resp.error) {
                infoboxError('This <strong>Username</strong> is already in use. Please make another choice.', 'cf-uname');
                $("#save_uname").css('visibility', 'hidden');
            } else {
                $("#save_uname").css('visibility', 'visible');
            }
            if(subm) {
                var back_url = $("#back_url").val() != '/account/post.php?' ? $("#back_url").val() : $("#post_isbn").val();
                var form = $("<form id='hidden_form' method='post' action='/account/register.php'>" +
                    "<input type='hidden' name='action' value='add_username' />" +
                    "<input type='hidden' name='back_url' value='"+back_url+"' />" +
                    "<input type='hidden' name='username' value='"+uname+"'>" +
                    "<input type='submit' value='Go' /></form>");

                $(document).find('body').append(form).hide();
                $("#hidden_form").submit();
            }
        }
    });

}


function validateUsername(uname) {
    var re = /[^A-Za-z0-9\s_-]/g;
    if (uname.length == 0) {
        infoboxError('<strong>Username</strong> can\'t be blank', 'cf-uname');
        return false;
    } else if (uname.toLowerCase() == 'textbookx buyer') {
        infoboxError('This <strong>Username</strong> is already in use. Please make another choice.', 'cf-uname');
        return false;
    } else if (re.test(uname)) {
        infoboxError('Your <strong>username</strong> entry was invalid. Please limit your entry to letters, numbers, spaces, dashes or underscores', 'cf-uname');
        return false;
    } else if (uname.length > 50) {
        infoboxError('Your <strong>username</strong> entry is too long. Please limit your entry to 50 characters or less.', 'cf-uname');
        return false;
    } else {
        return true;
    }
}

function submitUsername(can_save) {
    var uname = $('#cf-uname').val().toLowerCase();
    var ph = $('#cf-uname').attr('title');

    if (ph.toLowerCase() == uname) uname = "";

    if (validateUsername(uname)) {
        sendUsernameResponse(uname, can_save);
        return false;
    } else {
        $("#save_uname").css('visibility', 'hidden');
    }
}

/*
 ----- COMMON JS FUNCTIONS -----
 next part of code is for functions, available on all pages
 */


function doPlaceholder(elem, show) {
    if (show && elem.value == '') elem.value = elem.title;
    else if (elem.value == elem.title) elem.value = '';
    return false;
}

function ebookPopUp(url) {
    var height = /ebook_tbx/.test(url) ? 315 : 455;
    popupWin = window.open(url, 'ebookTooltip', 'width=400,height=' + height + ',scrollbars=no,toolbar=no,location=no,menubar=no,resizable=no,status=no');
    if (window.focus) {
        popupWin.focus();
    }
    return false;
}


//Google Analytics help code

GA_helper = function () {
    var that = this;

    this.getAction = function (url) {
        var r = /action=(\w+)/gi.exec(url);
        if (r === null) {
            r = /(add2cart)/gi.exec(url);
            return r !== null ? that.find(r[1]) : 'No action';
        } else {
            return that.find(r[1]);
        }
    };

    this.getCategory = function () {
        //var domain = String(window.location.host).split('.', 1)[0];
        if (true_domain == 'textbookx') {
            // || domain == 'ryurchik' should be removed before going live. This is only for testing
            //to detect dev textbookx site and it could be 'vraji', 'tdvoryanchenko', etc.
            return 'consumer-direct';
        } else {
            if (that.is_admin_mode()) return true_domain + '-admin';
            else return true_domain + '-student';
        }
    };

    this.action_map = {
        'alternateeditions':'Book\'s alternalte editions',
        'description':'Book description',
        'review':'Book reviews',
        'excerpts':'Book excerpts',
        'add2cart':'Add book to cart',
        'update':'Update shopping cart',
        'books':'Course booklist',
        'classes':'Classes list for department',
        'deps':'Departments listing',
        'instructors':'Instructors list',
        'admins':'Administrators list',
        'passwd':'Reset password for instructor',
        'courseAdd':'Add new course form',
        'courseAddInit':'Add new course - submit',
        'courseEdit':'Edit course form',
        'courseEditInit':'Edit course - submit',
        'courseRemoveInit':'Delete course',
        'bookAdd':'Add new book to course form',
        'bookAddInit':'Add new book to course - submit',
        'bookEdit':'Edit book form',
        'bookEditInit':'Edit book - submit',
        'bookRemoveInit':'Delete book from course',
        'documentAdd':'Add new file to course form',
        'documentAddInit':'Add new file to course - submit',
        'documentRemoveInit':'Remove file from course',
        'instructorAdd':'Add new instructor form',
        'instructorAddInit':'Add new instructor - submit',
        'instructorEdit':'Edit instructor form',
        'instructorEditInit':'Edit instructor - submit',
        'instructorRemoveInit':'Delete instructor',
        'instructionsEdit':'Edit ordering instructions form',
        'instructionsEditInit':'Edit ordering instructions - submit',
        'adminAdd':'Add new admin form',
        'adminAddInit':'Add new admin - submit',
        'adminEdit':'Edit admin form',
        'adminEditInit':'Edit admin - submit',
        'adminRemoveInit':'Delete admin',
        'departmentAdd':'Add new department form',
        'departmentAddInit':'Add new department - submit',
        'departmentEdit':'Edit department form',
        'departmentEditInit':'Edit department - submit',
        'departmentRemoveInit':'Delete department',
        'welcomeEdit':'Edit Welcome Greeting form',
        'welcomeEditInit':'Edit Welcome Greeting - submit',
        'featuredAdd':'Add featured item form',
        'featuredAddInit':'Add featured item - submit',
        'featuredRemove':'Remove featured item',
//Checkout part
        'proceedStart':'Proceed to customer information page',
        'proceedCheckout':'Proceed to shipment selection process page',
        'proceedPayment':'Proceed to payment selection page',
        'proceedReceipt':'Proceed to receipt page',
        'userLogin':'User logged in using Checkout',
        'backStart':'Returned to customer information page',
        'backCheckout':'Returned to shipment selection page',
        'backPayment':'Returned to payment selection page',
        'changedStart':'Checkout customer information page changed',
        'changedCheckout':'Checkout shipment selection changed',
        'savedPassword':'User saved password during checkout process'

    };

    this.find = function (val) {
        return that.action_map[val] ? that.action_map[val] : 'Unknown action :' + val;
    };

    this.is_admin_mode = function () {
        return document.getElementById('formLayer') === null ? false : true;//not the best solution
    }

    this.debug = false;
};

var ga_helper = new GA_helper;

