var ajaxServiceUrl = "/wcpa/servlet/org.oclc.lac.ui.ajax.ServiceServlet";

jQuery(document).ready(makeMaincolPageLoadComplete());	// located in maincol.jsp

function maincolPageLoadComplete(oclcNum, platformPage, localPage, displaySyndeticsData, enableSyndetics, buyItLink,
								suggestionsExist, enableSimilarItemsCarousel, socialAllowed, performanceMetrics) {
	
    // NEW pushDownDiv instance for all inline "Read more" links
    jQuery('.showMoreLessReadmore').showMoreLessDiv({
        expandedText:			'Moins de texte',
        contractedText:			'Lire la suite...',
        expandedControlStyle:	'expanded-control',
        contractedControlStyle:	'contracted-control',
        expandedContentStyle:	'expanded-content',
        contractedContentStyle:	'contracted-content'
    });
        
	// setup expanding/ contracting sections
	if (platformPage) {
		jQuery('#ecopy').expandoSection({
		 expandedImg:			'/wcpa/images/btn_dark_collapse.gif',
		 contractedImg:			'/wcpa/images/btn_dark_expand.gif',
		 expandedContentStyle:	'showMoreLessBox-dark-content-expanded'
		});
		
		jQuery('#links-all856').expandoSection({
		 expandedImg:			'/wcpa/images/btn_lite_collapse.gif',
		 contractedImg:			'/wcpa/images/btn_lite_expand.gif',
		 expandedText:			'Afficher uniquement les 3 premiers liens',
		 contractedText:			'Afficher tous les liens'
		});

		jQuery('#borrow').expandoSection({
			expandedImg:			'/wcpa/images/btn_dark_collapse.gif',
			contractedImg:			'/wcpa/images/btn_dark_expand.gif',
			expandedContentStyle:	'showMoreLessBox-dark-content-expanded'
		});
	}
	if (localPage) {
		jQuery('#borrow').expandoSection({
			expandedImg:			'/wcpa/images/btn_dark_collapse.gif',
			contractedImg:			'/wcpa/images/btn_dark_expand.gif',
			expandedContentStyle:	'showMoreLessBox-grey-content-expanded'
		});
	}
	jQuery('#details').expandoSection({
		expandedImg:			'/wcpa/images/btn_lite_collapse.gif',
		contractedImg:			'/wcpa/images/btn_lite_expand.gif',
		expandedContentStyle:	'showMoreLessBox-grey-content-expanded'
	});

    //1st-level expandoSection instance - expanded for both local and platform
    if (platformPage || (localPage && displaySyndeticsData && enableSyndetics)) {
        jQuery('#reviews').expandoSection({
            expandedImg:			'/wcpa/images/btn_lite_collapse.gif',
            contractedImg:			'/wcpa/images/btn_lite_expand.gif',
            expandedContentStyle:	'showMoreLessBox-grey-content-expanded'
        });
    } else {
        jQuery('#reviews').expandoSection({
            expandedImg:			'/wcpa/images/btn_lite_collapse.gif',
            contractedImg:			'/wcpa/images/btn_lite_expand.gif',
            initialStateContracted:	true
        });
    }
	if (localPage) {
        //2nd-level expandoSection instances for local editorial/user review breakout
        jQuery('#rev-editor').expandoSection({
            expandedImg:			'/wcpa/images/btn_arrow_collapse.png',
            contractedImg:			'/wcpa/images/btn_arrow_expand.png'
        });
        jQuery('#rev-users').expandoSection({
            expandedImg:			'/wcpa/images/btn_arrow_collapse.png',
            contractedImg:			'/wcpa/images/btn_arrow_expand.png',
            initialStateContracted:	true            
        });
	}
	jQuery('#tags').expandoSection({
		expandedImg:			'/wcpa/images/btn_lite_collapse.gif',
		contractedImg:			'/wcpa/images/btn_lite_expand.gif',
		expandedContentStyle:	'showMoreLessBox-grey-content-expanded'
	});
	jQuery('#similar').expandoSection({
		expandedImg:			'/wcpa/images/btn_lite_collapse.gif',
		contractedImg:			'/wcpa/images/btn_lite_expand.gif',
		expandedContentStyle:	'showMoreLessBox-grey-content-expanded'
	});
	jQuery('.showMoreLessBox-socutil').expandoSection({
		expandedImg:				'/wcpa/images/btn_orange_collapse.gif',
		contractedImg:				'/wcpa/images/btn_orange_expand.gif',
		expandedContentStyle:		'showMoreLessBox-socutil-content-expanded',
		initialStateContracted:		true
	});

	// setup push down divs
	jQuery('#showApplyTags').pushDownDiv({
		expandedImg:				'/wcpa/images/btn_lite_collapse.gif',
		contractedImg:				'/wcpa/images/btn_lite_expand.gif',
		expandedText:				"Assigner des tags que j’ai déjà créés",
		contractedText:				"Assigner des tags que j’ai déjà créés"
    }); 
	jQuery('.showMoreLessBlock').pushDownDiv({
		expandedImg: 			'/wcpa/images/btn_lite_collapse.gif',
		contractedImg:			'/wcpa/images/btn_lite_expand.gif',
		expandedText:			'Moins',
		contractedText:			'Plus'
	});
	jQuery('.libGlobalLookup').pushDownDiv({
		expandedImg: 			'/wcpa/images/btn_lite_collapse.gif',
		contractedImg:			'/wcpa/images/btn_lite_expand.gif',
		expandedText:			'Des bibliothèques à travers le monde possèdent cet ouvrage',
		contractedText:			'Des bibliothèques à travers le monde possèdent cet ouvrage'
	});
	jQuery('#showLocalSvcs').pushDownDiv({
		expandedImg: 			'/wcpa/images/btn_lite_collapse.gif',
		contractedImg:			'/wcpa/images/btn_lite_expand.gif',
		expandedText:			'Cacher les services locaux pour cet ouvrage',
		contractedText:			'Afficher les services locaux pour cet ouvrage'
	   });

    if (performanceMetrics)
    	jQuery('#browserLoadTimes table').append(jQuery('<tr><td>Main Column section</td><td>' + ((new Date()).getTime() - mainColSectionBeginTime) + '</td></tr>'));

	// load buy it links
    if (buyItLink) {
    var ajaxBuyingServiceUrl = "/wcpa/servlet/org.oclc.lac.ui.buying.AjaxBuyingLinksServlet";

	jQuery.get(ajaxBuyingServiceUrl, {serviceCommand: 'getBuyingLinks', oclcno: oclcNum }, function(data) {
		// update buying links html
		jQuery('#buyinglinks').html(data);
		// setup expanding/ contracting sections
		if (platformPage) {
			jQuery('#buyit').expandoSection({
				expandedImg:			'/wcpa/images/btn_dark_collapse.gif',
				contractedImg:			'/wcpa/images/btn_dark_expand.gif',
				expandedContentStyle:	'showMoreLessBox-dark-content-expanded'
			});
		}
		if (localPage) {
			jQuery('#buyit').expandoSection({
				expandedImg:			'/wcpa/images/btn_dark_collapse.gif',
				contractedImg:			'/wcpa/images/btn_dark_expand.gif',
				expandedContentStyle:	'showMoreLessBox-local-content-expanded',
				initialStateContracted:	true
			});
			
			jQuery('#buyit h2').attr('style', '${custom.bannerBckgrndColor} ${custom.bannerLinkColor}');
		}

        if (data.indexOf("BUYING_FLAG") != -1) {
            var inp = document.getElementById("jumptobuying");
            if(inp) inp.style.display= 'inline';
        }
    });
    }

    jQuery('.libGlobalLookup').bind('expanded',(function(){ findLibsWhenExpanded(); }));
    // load social items: reviews and lists
    jQuery('#rev-users').bind('expanded', (function(){ getAllReviews(); }));
    loadLists(oclcNum);
    loadWeRead();
        
	// Similar Items Section
	// for Local
	
	if (localPage && suggestionsExist && enableSimilarItemsCarousel && socialAllowed) {
		// search for and fill in fill in Browse similar items... subsection
		var aSeriesItem = '<span class="series">Aussi dans cette collection</span>\
<a href="/oclc/{oclcNum1}?ref=similarItems" title="Titre" onClick="LibServices(this,\'wctlink_related_series\',\';wctlink_related_series\');"><img border="0" src="{coverArtUrl}" width="72" height="92" alt=""></a>\
<p><a href="/oclc/{oclcNum2}?ref=similarItems" onClick="LibServices(this,\'wctlink_related_series\',\';wctlink_related_series\');">{title}</a> de {author}</p>';

		var anAuthorItem = '<span class="auth">Par le ou les mêmes auteurs</span>\
<a href="/oclc/{oclcNum1}?ref=similarItems" title="Titre" onClick="LibServices(this,\'wctlink_related_author\',\';wctlink_related_author\');"><img border="0" src="{coverArtUrl}" width="72" height="92" alt=""></a>\
<p><a href="/oclc/{oclcNum2}?ref=similarItems" onClick="LibServices(this,\'wctlink_related_author\',\';wctlink_related_author\');">{title}</a> de {author}</p>';

		var aSubjectItem = '<span class="subj">Sur le ou les mêmes sujets</span>\
<a href="/oclc/{oclcNum1}?ref=similarItems" title="Titre" onClick="LibServices(this,\'wctlink_related_subject\',\';wctlink_related_subject\');"><img border="0" src="{coverArtUrl}" width="72" height="92" alt=""></a>\
<p><a href="/oclc/{oclcNum2}?ref=similarItems" onClick="LibServices(this,\'wctlink_related_subject\',\';wctlink_related_subject\');">{title}</a> de {author}</p>';


    	
    	jQuery.get(ajaxServiceUrl, {serviceCommand: 'getBrowseSimilarItems', oclcnum: oclcNum}, function(data) {
    		var similiarItems = YAHOO.lang.JSON.parse(data);

    		carouselItem = { content: "", className: "item"	};
    		var carousel = new YAHOO.widget.Carousel("container", {animation: {speed: 0.5 } });

    		for (var i = 0; i < similiarItems.similarBySeries.length; i++) {
        		var recordLight = similiarItems.similarBySeries[i];
            	carouselItem.content = aSeriesItem.replace('{title}', recordLight.title)
	                .replace('{author}', recordLight.authorFullName)
    	            .replace('{oclcNum1}', recordLight.oclcNum)
        	        .replace('{oclcNum2}', recordLight.oclcNum)
            	    .replace('{coverArtUrl}', recordLight.coverArtURL);
		        carousel.addItem(carouselItem);
    		}
			
    		for (var i = 0; i < similiarItems.similarByAuthor.length; i++) {
        		var recordLight = similiarItems.similarByAuthor[i];
            	carouselItem.content = anAuthorItem.replace('{title}', recordLight.title)
	                .replace('{author}', recordLight.authorFullName)
    	            .replace('{oclcNum1}', recordLight.oclcNum)
        	        .replace('{oclcNum2}', recordLight.oclcNum)
            	    .replace('{coverArtUrl}', recordLight.coverArtURL);
		        carousel.addItem(carouselItem);
    		}
    		
    		for (var i = 0; i < similiarItems.similarBySubject.length; i++) {
        		var recordLight = similiarItems.similarBySubject[i];
            	carouselItem.content = aSubjectItem.replace('{title}', recordLight.title)
	                .replace('{author}', recordLight.authorFullName)
    	            .replace('{oclcNum1}', recordLight.oclcNum)
        	        .replace('{oclcNum2}', recordLight.oclcNum)
            	    .replace('{coverArtUrl}', recordLight.coverArtURL);
		        carousel.addItem(carouselItem);
    		}
    		
    		carousel.set("numVisible", 5);
    		carousel.render();
    		carousel.show();
    		
    	});
	}
	
}

function mlog(msg) {
	if (window.console && window.console.log) {
		window.console.log('[OWC-MAINCOL.JSP]- ' + msg);
	}

};

function toggleSuggest(){
    var currentStatus = document.getElementById("autocompleteStatus");
    var toggleLink = document.getElementById("autocompleteToggle");
    if(currentStatus.innerHTML == "activée")
    {
        currentStatus.innerHTML = "désactivée";
        toggleLink.innerHTML = "Activer";
        document.getElementById("autocomplete").id = "autocompleteOff";
	} else {
        currentStatus.innerHTML = "activée";
        toggleLink.innerHTML = "Désactiver";
        document.getElementById("autocompleteOff").id = "autocomplete";
	}
};

	// Tags section
	function changeTagListView(oclcno){
	    document.getElementById('taglistview').style.display = "block";
	    document.getElementById('tagcloudview').style.display = "none";
	    document.getElementById('tagcloudtext').style.display = "none";
	    document.getElementById('taglisttext').style.display = "block";
	    //send back to servlet to record the tag view
	    recordTagView(oclcno, "list");
	}

	function changeTagCloudView(oclcno){
	    document.getElementById('taglistview').style.display = "none";
	    document.getElementById('tagcloudview').style.display = "block";
	    document.getElementById('taglisttext').style.display = "none";
	    document.getElementById('tagcloudtext').style.display = "block";
	    //send back to servlet to record the tag view
	    recordTagView(oclcno, "tagcloud");
	}

	function recordTagView(oclcno, tagview){
	    jQuery.post("/oclc/" + oclcno, {tagview: tagview});
	}

    function closeAddTagsUtil(){
        jQuery('#addtagsutil').click();
        document.getElementById('TagEntry').value = '';
        document.getElementById('error_entertagsandapply_tagsection').style.display = "none";
        document.getElementById('savetagerror_tagsection').style.display = "none";
        return false;
    }

function forwardToIdentities() {
	var toURL = jQuery('#authorSearchSelect')[0].value;
	LibServices(toURL, 'wctlink_identities', ';wctlink_identities');
	window.location = toURL;
}

/* Begin Google Book API */
function ProcessGBSBookInfo(booksInfo) {
 var oclcno = GOOGLE_OBJECT.oclcno;
 var ISBN1 = GOOGLE_OBJECT.ISBN1;
 var language = GOOGLE_OBJECT.language;

 for (isbn in booksInfo) {
  var fullText = "Voir l’ouvrage intégral via Google Books";
  var partText = "Voir un extrait de cet ouvrage via Google Books";
  var displayText = "";
  var displayUrl = "";
  var embed = false;
  var bookInfo = booksInfo[isbn];
  if (bookInfo == null) continue;

  if (bookInfo.preview == "full") {
   displayText = fullText;
  } else if (bookInfo.preview == "partial") {
   displayText = partText;
  }else{
   continue;
  }

  if (bookInfo.embeddable != null && bookInfo.embeddable == true) {
   embed = true;
  }
  if (embed) {
   displayUrl = "/oclc/" + oclcno + "/viewport";
   var bib_key = bookInfo.bib_key;
   if (bib_key && bib_key.indexOf (ISBN1)==-1 && bib_key.indexOf(oclcno)==-1) {
     displayUrl += "?bib_key=" + bib_key;
   }
  } else {
   displayUrl = bookInfo.preview_url;
  }
  var displayImage = "/wcpa/images/gbs_preview_button1_" + language + ".png";

  // Display Google Book Button for local
  var elementBtn = document.getElementById("GoogleBtn");
  var btnHtml = "";
  if (embed) {
   btnHtml += '<a href="'+ displayUrl + '" onclick="LibServices(this, \'wctlink_googleBooksViewer\', \';wctlink_googleBooksViewer\');">' +
             '<img src="'+ displayImage + '" border="0" alt="' + displayText + '" title="' + displayText + '" align="absmiddle">' + '</a>';
  } else { // only difference is to add a blank target
   btnHtml += '<a target="_blank" href="'+ displayUrl + '" onclick="LibServices(this, \'wctlink_googleBooksViewer\', \';wctlink_googleBooksViewer\');">' +
             '<img src="'+ displayImage + '" border="0" alt="' + displayText + '" title="' + displayText + '" align="absmiddle">' + '</a>';
  }
  if (elementBtn) {
   if (document.getElementById("item-preview")) {
    document.getElementById("item-preview").style.display = "block";
   }
   elementBtn.innerHTML = btnHtml;
   elementBtn.style.display = "block";
  }

  if (displayUrl) break;
 }
}

function getGoogleKey (ISBN, oclcNumber) {
  var returnKey = "";
  var mySplitResult = ISBN.split(" ");

  for(var i = 0; i < mySplitResult.length; i++){
    var result = trimAll(mySplitResult[i]);
    if(result!="") {
     if (i!=0) returnKey += ",";
     returnKey += "ISBN:" + trimAll(mySplitResult[i]);
    }
  }

  if (returnKey == "") {
    returnKey = "OCLC:" + oclcNumber;
  } else {
    returnKey += ",OCLC:" + oclcNumber;
  }
  return returnKey;
}

var GoogleCalled = false;
function searchGoogle(query) {
    if (GoogleCalled) return;

    // Delete any previous Google Book Search JSON queries.
    var jsonScript = document.getElementById("jsonScript");
    if (jsonScript) {
        jsonScript.parentNode.removeChild(jsonScript);
    }

    // Add a script element with the src as the user's Google Book Search query.
    // JSON output is specified by including the alt=json-in-script argument
    // and the callback function is also specified as a URI argument.
    var scriptElement = document.createElement("script");
    scriptElement.setAttribute("id", "jsonScript");
    scriptElement.setAttribute("src",
    "http://books.google.com/books?bibkeys=" +
    query + "&jscmd=viewapi&callback=ProcessGBSBookInfo");
    scriptElement.setAttribute("type", "text/javascript");
    // make the request to Google Book Search
    document.documentElement.firstChild.appendChild(scriptElement);

    GoogleCalled = true;
}
/* End Google Book API */

/* Begin Delivery Resolver Availability Section */
var reqItemLink;
var openNewWin;

function checkDuplicateClick(dest, newWindow, checksum) {
    var checksums = getCookie("req_button_ids");
    var checksumTokens = checksums.split(",");
    for (var i = 0; i < checksumTokens.length; i++)
    {
        if (checksumTokens[i] == checksum) {
            reqItemLink = dest;
            openNewWin = newWindow;
            showConfirmDiv("req_confirmation");
            LibServices(this,'request_alert',';request_alert');
            return;
        }
    }

    if(checksums != null && checksums.length>0)
        setCookie("req_button_ids", checksums+","+checksum);
    else
        setCookie("req_button_ids", checksum);

    if(newWindow)
        MM_openBrWindow(dest, '', 'status=yes,menubar=yes,scrollbars=yes,resizable=yes');
    else
        MM_goToURL('parent', dest);
}

function showConfirmDiv(id) {
    if (id != null && document.getElementById(id)) {
        document.getElementById(id).style.display = "block";
        if (document.getElementById("confirm_ok"))
            document.getElementById("confirm_ok").focus();
    }
}

function hideConfirmDiv(id, isOkBtn) {
    if (id != null && document.getElementById(id))
        document.getElementById(id).style.display = "none";

    //go to next page
    if(isOkBtn){
        if(openNewWin)
            MM_openBrWindow(reqItemLink, '', 'status=yes,menubar=yes,scrollbars=yes,resizable=yes');
        else
            MM_goToURL('parent', reqItemLink);
    }
}

function getLocalFulfillmentLink (link, newWindow, checksum) {
  if (checksum == '') { // bypass div layer
    if (newWindow==true) {
      MM_openBrWindow(link, '', 'status=yes,menubar=yes,scrollbars=yes,resizable=yes');
    } else {
      MM_goToURL('parent',link);
    }
  } else {
    checkDuplicateClick (link, newWindow, checksum);
  }
}

/* End Delivery Resolver Availability Section */
