//////////////////////////////////////
// variables
//////////////////////////////////////

var backToPrevious = false;
var lastScrollTop = 0;

//////////////////////////////////////
// event handlers
//////////////////////////////////////

function addToCart(productCode, productType) {
  if (! top.mainFrame) top.location = "/resultsframe.asp?u=" + window.location + "?js=addToCart(" + productCode + "," + productType + ")"
  else {
    if (window.pageTracker) pageTracker._trackEvent("Image", "Add to Cart", productCode); // Track Event in Google
    var frame = window.opener? window.opener.parent.frames[1]: parent.frames[1];
    if (frame.defaultCart)
      frame.defaultCart.Items.add(productCode, productType);
    else {
      document.iframecartaddform.atsc.value = productCode;
      document.iframecartaddform.imageType.value = productType;
      document.iframecartaddform.submit();
    }
  }
}

function addToLightbox(productCode) {
  if (! top.mainFrame) top.location = "/resultsframe.asp?u=" + window.location + "?js=addToLightbox(" + productCode + ")"
  else {
    if (window.pageTracker) pageTracker._trackEvent("Image", "Add to Lightbox", productCode); // Track Event in Google
    var frame = window.opener? window.opener.parent.frames[1]: parent.frames[1];
    if (frame.defaultLB)
      frame.defaultLB.Images.add(productCode);
    else {
      var pb;
      try {
        pb = GetCurrentLightboxName();
      }
      catch(e) {
        pb = '';
      }
      document.iframeaddform.add.value = '1';
      document.iframeaddform.image.value = productCode;
      document.iframeaddform.pb.value = pb;
      document.iframeaddform.submit();
    }
  }
}

function addAllToLightbox() {
    var pageStart = Ext.get('rsPageStart').getValue(true) + 1;
    var pageEnd = Ext.get('rsPageEnd').getValue(true);
    var imgIDs = '';
    var n = 0;
    for (n = pageStart; n <= pageEnd; n++) {
        var id = GetImageID(n);
        if (imgIDs.length > 0) {
            imgIDs = imgIDs + '|' + id;
        }
        else {
            imgIDs = id;
        }
    }
    if (n > 1) {
        var pb;
        try {
            pb = GetCurrentLightboxID();
        }
        catch(e){
            pb = '';
        }

        var frame = window.opener? window.opener.parent.frames[1]: parent.frames[1];

        if (frame.defaultLB)
        	frame.defaultLB.Images.addRange(imgIDs);
        else {
	        document.iframeaddform.add.value = n;
	        document.iframeaddform.image.value = imgIDs;
	        document.iframeaddform.pb.value = pb;
	        document.iframeaddform.submit();
        }
    }
}

/*
function doSearch() {
    var success = false;
    saveSearch();
    if (myBrowser.supportsAJAX()) {
        try {
            var frm = document.CDStoreForm ? $('CDStoreForm') : $('frmSearch');
            var fields = checkFields(getFormFields(frm));
            var params = $H(Form.serializeElements(fields, true));
            if (document.frmSearch) {
                params.set('lstImageType', frm.lstImageType.selectedIndex + 1);
                params.set('pixperpage', frm.pixperpage.options[frm.pixperpage.selectedIndex].value);
            }
            else if (document.CDStoreForm) {
                params.set('cat', getSelectedValues($('cat')));
                for (n=0; n<=70; n++) {params.unset('fotog' + n)};
            }

            var url = getURL('/controllers/ss_search.asp');
            var qs = '/Results.asp?' + buildQueryString(params._object);

            pageTracker._trackPageview(qs);
            startDownload();
            new Ajax.Updater( {success: 'searchResults'}, url, {
                parameters: params,
                onSuccess: updatePage,
                onFailure: handleAjaxServerError,
                onException: handleAjaxClientError
                });
            success = true;
        }
        catch(e) { success = false; }
    }
    return success;
}
*/
function buildQueryString(params) {
	var ret = '';
	for(obj in params) {
		if (ret.length > 0) ret += '&';
		ret += obj + "=" + params[obj];
	}
	
	return ret;
}

function getNextPage() {
    var thisPage = new Number(document.getElementById('rsThisPage').value);
    var pageCount = new Number(document.getElementById('rsPageCount').value);
    if (thisPage < pageCount) {
        getPage(thisPage + 1);
    }
}

function getNumberedPage(elem) {
    var pageCount = new Number(document.getElementById('rsPageCount').value);
    var pageNum = elem.value;
    if (pageNum <= 0) {
        pageNum = 1;
    }
    else if (pageNum > pageCount) {
        pageNum = pageCount;
    }
    document.getElementById('gotopage1').value = pageNum;
    document.getElementById('gotopage2').value = pageNum;
    getPage(pageNum);
}

function getPage(pageNum) {
    getSearch();
    var frm = document.CDStoreForm ? document.CDStoreForm : document.frmSearch;
    frm.pagenum.value = pageNum;
    //frm.viewSimilars.value = document.getElementById('rsSimilarImage').value;
    //frm.smltimage.value = document.getElementById('rsSMLTImage').value;
    //frm.smltcd.value = document.getElementById('rsSMLTCD').value;
    if (document.frmSearch) {
        frm.cat.value = document.getElementById('rsCategoryFilter').value;
        frm.fotog.value = document.getElementById('rsVendorFilter').value;
    }
    if (!doSearch()) {
        frm.submit();
    }
}

function getPreviousPage() {
    var thisPage = new Number(document.getElementById('rsThisPage').value);
    if (thisPage > 1) {
        getPage(thisPage - 1);
    }
}

function getPreviousSearch() {
    resetForm();
    getSearch();
    var frm = document.CDStoreForm ? document.CDStoreForm : document.frmSearch;
    if (frm.prevpagenum.value.length > 0) {
        frm.pagenum.value = frm.prevpagenum.value;
        frm.prevpagenum.value = '';
    }
    if (!doSearch()) {
        frm.submit();
    }
    else {
        backToPrevious = true;
    }
}

function getSearch() {
    if (document.frmSearch) {
        document.frmSearch.txtkeys1.value = document.frmSearch.txtkeys1save.value;
        document.frmSearch.txtkeys1prev.value = document.frmSearch.txtkeys1prevsave.value;
        if (document.frmSearch.searchbysave.value == '1') {
            document.getElementById('optSearchBy_ProductCode').checked = true;
            ChangeSearchOption(document.getElementById('optSearchBy_ProductCode'));
        }
        else {
            //document.getElementById('optSearchBy_Keyword').checked = true;
            //ChangeSearchOption(document.getElementById('optSearchBy_Keyword'));
        }
        if (document.frmSearch.searchinsave.value == '1') {
            document.getElementById('within2').checked = true;
        }
        else {
            document.getElementById('within1').checked = true;
        }
        if (document.frmSearch.showsimssave.value == '1') {
            //document.getElementById('optSimilars_Show').checked = true;
        }
        else {
            //document.getElementById('optSimilars_Hide').checked = true;
        }
        document.frmSearch.lstImageType.selectedIndex = document.frmSearch.imagetypesave.value - 1;
        document.frmSearch.chkRMFilter.checked = document.frmSearch.showrmsave.value == 'RM' ? true : false;
        document.frmSearch.chkRFFilter.checked = document.frmSearch.showrfsave.value == 'RF' ? true : false;
        document.frmSearch.imgextra1.checked = document.frmSearch.showcontemporarysave.value == '1' ? true : false;
        document.frmSearch.imgextra2.checked = document.frmSearch.showvintagesave.value == '2' ? true : false;
        document.frmSearch.imgextra3.checked = document.frmSearch.showfineartsave.value == '3' ? true : false;
        document.frmSearch.imgextra0.checked = document.frmSearch.showallsave.value == 'ALL COLLECTIONS' ? true : false;
        document.frmSearch.chkorientsh.checked = document.frmSearch.showhorizontalsave.value == 'Horizontal' ? true : false;
        document.frmSearch.chkorientsv.checked = document.frmSearch.showverticalsave.value == 'Vertical' ? true : false;
        document.frmSearch.chkbw.checked = document.frmSearch.showbwsave.value == 'BW' ? true : false;
        document.frmSearch.chkcolor.checked = document.frmSearch.showcolorsave.value == 'Color' ? true : false;
    }
}

function hideCaptionTooltip() {
    var tip = $('product-caption-tooltip');
    tip.innerHTML = '';
    tip.hide();
}

function hideErrorDetail() {
    Ext.get('searchErrorDetail').hide();
}

function hideErrorMessage() {
    hideErrorDetail();
    $('searchError').hide();
}

function includeSimilarsInResults() {
    var includeSimilars = false;
    if (document.frmSearch) {
        //var optSs = document.getElementById('optSimilars_Show');
        includeSimilars = true; //optSs.checked;
    }
    return(includeSimilars);
}

function isProductCodeSearch() {
    var productSearch = false;
    if (document.frmSearch) {
        //var optPc = document.getElementById('optSearchBy_ProductCode');
        productSearch = false; //optPc.checked;
    }
    return(productSearch);
}

function isSearchWithinResults() {
    var searchWithin = false;
    if (document.frmSearch) {
        //var optKw = document.getElementById('optSearchBy_Keyword');
        var optWi = document.getElementById('within2');
        searchWithin = optWi.checked; //optKw.checked && 
    }
    return(searchWithin);
}

function isValidPageKey(evt) {
    var key = evt.keyCode ? evt.keyCode : evt.which;
    if (key == Event.KEY_RETURN) {
        getNumberedPage(Event.element(evt));
        return true;
    }
    else {
        return isValidNumericKey(evt);
    }
}

function resetForm() {
    var frm = document.CDStoreForm ? document.CDStoreForm : document.frmSearch;
    frm.pagenum.value = '1';
    frm.smltimage.value = '';
    frm.smltcd.value = '0';
    frm.viewSimilars.value = '0';
    frm.loadPreview.value = '';
}

function saveSearch() {
    if (document.frmSearch) {
        saveKeywords();
        document.frmSearch.searchbysave.value           = isProductCodeSearch() ? '1' : '0';
        document.frmSearch.searchinsave.value           = isSearchWithinResults() ? '1' : '0';
        document.frmSearch.showsimssave.value           = includeSimilarsInResults() ? '1' : '0';
        document.frmSearch.imagetypesave.value          = document.frmSearch.lstImageType.selectedIndex + 1;
        document.frmSearch.showrmsave.value             = document.frmSearch.chkRMFilter.checked ? 'RM' : '';
        document.frmSearch.showrfsave.value             = document.frmSearch.chkRFFilter.checked ? 'RF' : '';
        document.frmSearch.showallsave.value            = document.frmSearch.imgextra0.checked ? 'ALL COLLECTIONS' : '';
        document.frmSearch.showcontemporarysave.value   = document.frmSearch.imgextra1.checked ? '1' : '';
        document.frmSearch.showvintagesave.value        = document.frmSearch.imgextra2.checked ? '2' : '';
        document.frmSearch.showfineartsave.value        = document.frmSearch.imgextra3.checked ? '3' : '';
        document.frmSearch.showhorizontalsave.value     = document.frmSearch.chkorientsh.checked ? 'Horizontal' : '';
        document.frmSearch.showverticalsave.value       = document.frmSearch.chkorientsv.checked ? 'Vertical' : '';
        document.frmSearch.showbwsave.value             = document.frmSearch.chkbw.checked ? 'BW' : '';
        document.frmSearch.showcolorsave.value          = document.frmSearch.chkcolor.checked ? 'Color' : '';
    }
}

function saveKeywords() {
    var kwNew = document.frmSearch.txtkeys1.value.toLowerCase();
    try { kwNew = kwNew.replace(/^\s+|\s+$/g,''); }catch(e){};

    var kwSave = document.frmSearch.txtkeys1save.value.toLowerCase();
    try { kwSave = kwSave.replace(/^\s+|\s+$/g,''); }catch(e){};

    var kwPrev = document.frmSearch.txtkeys1prev.value;
    try { kwPrev = kwPrev.replace(/^\s+|\s+$/g,''); }catch(e){};

    if (kwNew != kwSave) {
        if (isSearchWithinResults()) {
            if (kwPrev != kwSave) {
                kwPrev += ' AND ' + kwSave;
            }
        }
        else {
            kwPrev = '';
        }
        document.frmSearch.txtkeys1save.value = kwNew;
        document.frmSearch.txtkeys1prev.value = kwPrev;
        document.frmSearch.txtkeys1prevsave.value = kwPrev;
    }
}
/*
function setKeywordsFromList(kw) {
    resetForm();
    document.frmSearch.txtkeys1.value = kw;
    if (CheckSubmit()) {
        document.frmSearch.submit();
    }
}
*/
function showCaptionTooltip(evt, elem) {
    //var cap = Ext.get(elem).down('div');
    //var tip = Ext.get('product-caption-tooltip');
    //tip.innerHTML = cap.innerHTML;
    //tip.clonePosition(elem, {setWidth:false,setHeight:false,offsetLeft:-25});
    //tip.show();
}

function showCD(productCode) {
    var attr = 'status=yes,scrollbars=yes,resizable=yes,directories=no,toolbar=no,menubar=no,height=625,width=988,top=10,left=10';
    var url  = '/results.asp?pagenum=1&viewCD=' + productCode;
    window.open(url, productCode.replace(/-/, ''), attr);
}

function showComp(productName, productType) {
    var url = productType == 3 ? '/rp.asp' : '/rf.asp';
    url += '?image=' + productName;
    window.open(url, "LicenseInfo"
	, "width=400, height=346, scrollbars=0, location=0, resizable=0"
    );
}

function showErrorDetail(evt) {
    var errDtl = Ext.get('searchErrorDetail');
	errDtl.show();
}

function showErrorMessage(msg) {
    stopDownload();
    var errDtl = $('searchErrorDetail');
    if (msg == null || msg.length == 0) {
        msg = 'Detailed error message not available';
    }
    errDtl.down('div#searchErrorDetailText').innerHTML = msg;
    $('searchError').show();
}

function showMoreLikeThis(productID, isCD) {
    var frm = document.CDStoreForm ? document.CDStoreForm : document.frmSearch;
    frm.prevpagenum.value = frm.pagenum.value;
    resetForm();
    frm.smltimage.value = productID;
    frm.smltcd.value = isCD;
    getSearch();
    if (!doSearch()) {
        frm.submit();
    }
    else {
        try {
            lastScrollTop = document.viewport.getScrollOffsets()[1];
        }
        catch(e) {}
    }
}

function showProduct(index, productType, productID, productCode) {
    if (window.pagetracker) pageTracker._trackEvent("Image", "Image Preview", productID); // Track Event in Google
    var attr = 'status=yes,scrollbars=yes,resizable=yes,directories=no,toolbar=no,menubar=no,height=625,width=988';
    var frm = document.CDStoreForm ? document.CDStoreForm : document.frmSearch;
    var url  = '/preview.asp?image=' + productCode + '&imagex=' + index + '&id=' + productID + '&productType=' + productType;
        url += '&pageStart=' + document.getElementById('rsPageStart').value;
        url += '&pageEnd=' + document.getElementById('rsPageEnd').value;
        url += '&pixperpage=' + document.getElementById('rsPageSize').value;
        url += '&hitCount=' + document.getElementById('rsHitCount').value;
        url += '&filterForCat=' + document.getElementById('rsCategoryFilter').value;
        url += '&filterForFotog=' + document.getElementById('rsVendorFilter').value;
    window.open(url, productID, attr);
}

function showSMLTProduct(productType, productID, productCode) {
    var attr = 'status=yes,scrollbars=yes,resizable=yes,directories=no,toolbar=no,menubar=no,height=625,width=895,top=10,left=10';
    var url  = '/preview.asp?image=' + productCode + '&imagex=1' + '&id=' + productID + '&productType=' + productType;
        url += '&pageStart=1&pageEnd=1&pixperpage=1&hitCount=1';
        url += '&filterForCat=' + document.getElementById('rsCategoryFilter').value;
        url += '&filterForFotog=' + document.getElementById('rsVendorFilter').value;
    window.open(url, productID, attr);
}

function showSimilars(productCode, productIndex, similarID) {
    var frm = document.CDStoreForm ? document.CDStoreForm : document.frmSearch;
    frm.prevpagenum.value = frm.pagenum.value;
    resetForm();
    frm.viewSimilars.value = similarID;
    getSearch();
    if (!doSearch()) {
        frm.submit();
    }
    else {
        try {
            lastScrollTop = document.viewport.getScrollOffsets()[1];
        }
        catch(e) {}
    }
}

function showTip(toolTipID, toolIndex) {
   document.getElementById(toolTipID).src = '/images/overlay' + toolIndex + '.gif';
}

function startDownload() {
    hideErrorMessage();
    $$('div.search-results-loading').each(function(d) {
        d.show();
    });
}

function stopDownload() {
    $$('div.search-results-loading').each(function(d) {
        d.hide();
    });
}

//////////////////////////////////////
// utility functions
//////////////////////////////////////

function checkFields(arr) {
    var imageSearch = document.frmSearch ? true : false;
    if (imageSearch) {
        var elems = new Array(
            'txtkeys1',
            //'optSearchBy_Keyword', 'optSearchBy_ProductCode',
            'within1', 'within2', //'optSimilars_Hide', 'optSimilars_Show',
            'chkRMFilter', 'chkRFFilter',
            'imgextra0', 'imgextra1', 'imgextra2', 'imgextra3',
            'Checkbox4', 'Checkbox5', 'idchkbw', 'idchkcolor'
        );
        $A(elems).each(function(el){
            if ($(el) && !fieldInArray(arr, el)){
                arr[arr.length] = $(el);
            }
        });
    }
    return(arr);
}

function fieldInArray(arr, fld){
    var hasIt = false;
    $A(arr).each(function(f){
        if (f.id == fld) {
            hasIt = true;
            return;
        }
    });
    return(hasIt);
}

//////////////////////////////////////
// callback functions
//////////////////////////////////////

function updatePage(){
    var updCmd = 'window.scrollTo(0,0)';
    if (backToPrevious) {
        updCmd = 'window.scrollTo(0,' + lastScrollTop + ')';
        backToPrevious = false;
        lastScrollTop = 0;
    }
    setTimeout(updCmd, 250);

    var frm = document.CDStoreForm ? document.CDStoreForm : document.frmSearch;
    if (frm.loadPreview.value.length > 0) {
        updCmd = 'PreviewImageFromNewPage(\'' + frm.loadPreview.value + '\')';
        frm.loadPreview.value = '';
        setTimeout(updCmd, 500);
    }
}

//////////////////////////////////////
// helpers for preview page (legacy)
//////////////////////////////////////

function GetImageID(index) {
    var elemID = "Image_" + index;
    var elem, tag;
	try {
		elem = Ext.get(elemID);
        tag  = elem.down('span');
	} catch(e) {
		elem = document.getElementById(elemID);
		if (!elem) return null;
        tag  = elem.getElementsByTagName("span")[0];
	}
	
    return tag.id;
}

function GoToNewPage(pageNum) {
	gotoPage(pageNum);
	/*
    var frm = document.CDStoreForm ? document.CDStoreForm : document.frmSearch;
    var thisPage = new Number(document.getElementById('rsThisPage').value);
    var loadPreview = (pageNum < thisPage ? 'last' : 'first');
    frm.loadPreview.value = loadPreview;
    getPage(pageNum);
	*/
}

function PreviewImageFromNewPage(imagePos) {
    var pos = null;
    if (imagePos == 'first') {
        pos = document.getElementById('rsPageStart').value;
    }
    else if (imagePos == 'last') {
        pos = document.getElementById('rsPageEnd').value;
    }
    if (pos != null) { showProduct(pos, '', '', GetImageID(pos)); }
}
