
//Define the delimters
var ATTRIBUTE_DELIMETER = "-_-";
var ITEM_NUMBER_DELIMETER = "*.*";
var RECORD_DELIMETER = "-.-"; 

//Define the cookies names.
var CM_ITEMS_COOKIE = "CMItemsAttributes";
var CM_IS_FROM_RECENTLYVIEWED = "isFromRecentlyViewed";

// Define the cookie max life time.
var MAX_LIFE_IN_DAYS = 30; 

//Global variable used to set values
var cmItemWithAttributes ="";
var cmAttribute = "";
var cmProductID = "";

function getCmCategoryId () {
	var cmCategoryId = "";
	if (document.getElementById('cmCategoryId') != null) {
		cmCategoryId = document.getElementById('cmCategoryId').value;
	}
	return cmCategoryId;
}

function createProductViewTagOnLoad(totalReviewsCount, avgRating, buyAgainPercentage, productID){
	var isCategoryOnSale = "";
	if (document.getElementById('isCategoryOnSale') != null) {
		isCategoryOnSale = document.getElementById('isCategoryOnSale').value;
	}
	var isCrossSell = "";
	if ( document.getElementById('isCrossSell') != null ) {
		isCrossSell = document.getElementById('isCrossSell').value;
	}
	var recommendationStrategy = "";
	if ( document.getElementById('recommendationStrategy') != null ) {
		recommendationStrategy = document.getElementById('recommendationStrategy').value;
	}
	
	var isFromRecentlyViewed = cm_getCookieValue(CM_IS_FROM_RECENTLYVIEWED);
	if(isFromRecentlyViewed != '' && isFromRecentlyViewed == 'Y'){  //  Means that the PDP is coming from "Recently viewed"
		isFromRecentlyViewed = 'Y';
	}
	else{
		isFromRecentlyViewed = 'N';
	}
	cm_deleteCookie(CM_IS_FROM_RECENTLYVIEWED);
	
	var productName = "";
	if (document.getElementById('productName') != null) {
		productName = document.getElementById('productName').value;
	}
	var productMFPartNumber = "";
	if (document.getElementById('productMFPartNumber') != null) {
		productMFPartNumber = document.getElementById('productMFPartNumber').value;
	}
	var storeId = document.getElementById('storeId').value;
	cmProductID = productID;
	var corePageId = "Product:" +productID+"-"+productName;

	if(isCategoryOnSale == 1){
		isCategoryOnSale = "Y";
	}
	else{
		isCategoryOnSale = "N";
	} 
	
	var mayWeSuggest;
	if(isCrossSell == "true"){  //  Means that the PDP is coming from "May we suggest"
		mayWeSuggest = "Y";
	}
	else{
		mayWeSuggest = "N";
	}
	
	if(totalReviewsCount != null && totalReviewsCount > 0){
		var att1 = createAttributeDelimeters(1);
		var att5 = createAttributeDelimeters(5);
		var att3 = createAttributeDelimeters(3);
		var att4 = createAttributeDelimeters(4);
		cmAttribute = avgRating+att1+totalReviewsCount+att1+buyAgainPercentage+att5+mayWeSuggest+att1+isFromRecentlyViewed+att3+isCategoryOnSale+att1+att1+recommendationStrategy+att1+"N";  // "N" indicates that this is not from catalog quich shop
		cmItemWithAttributes = productID + ITEM_NUMBER_DELIMETER + cmAttribute;
	}
	else{
		var att1 = createAttributeDelimeters(1);
		var att7 = createAttributeDelimeters(7);
		var att4 = createAttributeDelimeters(4);
		var att3 = createAttributeDelimeters(3);
		cmAttribute = att7+mayWeSuggest+att1+isFromRecentlyViewed+att3+isCategoryOnSale+att1+att1+recommendationStrategy+att1+"N";  // "N" indicates that this is not from catalog quich shop
		cmItemWithAttributes = productID + ITEM_NUMBER_DELIMETER + cmAttribute;
	}
	cmCreateProductviewTag(corePageId, productMFPartNumber, productName, getCmCategoryId(), storeId, null, null,cmAttribute);
}

function createAttributeDelimeters(quantity){
	var emptyAttributes = "";
	for(i=0;i<quantity;i++){
		emptyAttributes = emptyAttributes+ATTRIBUTE_DELIMETER;
	}
	return emptyAttributes;
}

/**
 * Updated By: Ahmad Darwazeh - 12/22/10
 * Description: Updated to replace all occurrences of '-_-' by '|' in order to 
 *				make the cookie size smaller per JIRA WCS-46.
 */

function cm_createCookie(name, value, days) {

	value = replaceAll(value, "-_-", "|");
	
	if (days) {
		var date = new Date();
 	
 		date.setTime(date.getTime()+(days*24*60*60*1000));
	
		var expires = "; expires="+date.toGMTString();
 	} 
	else {
		var expires = "";
	}
	
	document.cookie = name+"="+value+expires+"; path=/";
}

/**
  * Retrieves the Coremetrics cookie per the name.
  */
function cm_getCookieValue(c_name){
	if(typeof(c_name) == "undefined" || c_name == "")
		return "";
	
	if (document.cookie.length>0){
	  c_start=document.cookie.indexOf(c_name + "=");
	  if (c_start!=-1){
	    c_start=c_start + c_name.length+1;
	    c_end=document.cookie.indexOf(";",c_start);
	    if (c_end==-1) c_end=document.cookie.length;
	    
	    // START: WCS-46: Updated to replace all '|' by '-_-' in order to get the required cookie value which will be sent to Coremetrics.
	    var cookieValue =  unescape(document.cookie.substring(c_start,c_end));
	    var replacedCookieValue = replaceAll(cookieValue, "|", "-_-");
	    return replacedCookieValue;
	    // END: WCS-46
	  }
	}
	return "";
}

/**
  * Created by: Ahmad Darwazeh, 12/22/2010
  * Description: Replaces all occurences of a substring with another substring. 
  * 			 Created per WCS-46.
  */
function replaceAll(source, stringToFind, stringToReplace) {
	var temp = source;
    var index = temp.indexOf(stringToFind);
    while (index != -1) {
        temp = temp.replace(stringToFind, stringToReplace);
        index = temp.indexOf(stringToFind);
    }
    return temp;
}

/**
  * Delete the cookie per the name.
  */
function cm_deleteCookie(c_name){
	var d = new Date();
    document.cookie = c_name+"=;expires=" + d.toGMTString() + "; path=/;";
}

/**
  * Delete all cookies related to CM explore
  */
function deleteAllCMCookies(){
    cm_deleteCookie(CM_ITEMS_COOKIE);
    cm_deleteCookie("CMActionShop5Tag");
    cm_deleteCookie("CMActionShop9Tag");
    cm_deleteCookie("CMOrderTag");
    cm_deleteCookie(CM_IS_FROM_RECENTLYVIEWED);
}

function cm_getTheRecord(my_itemParentId){
	var record = '';
	var itemIndex = itemsIndexes[my_itemParentId];
	if(itemIndex == null || itemIndex == '' || typeof(itemIndex) == "undefined"){
		itemsIndexes[my_itemParentId] = 0;
	}
			
	var found =false;
	for(var i=0; i<splittedCookie.length && !found ; i++)  
	{
		if(splittedCookie[i].match(my_itemParentId) && itemsIndexes[my_itemParentId] <= i)
		{
			itemsIndexes[my_itemParentId] = i+1;
			record = splittedCookie[i];
			found = true;
		}
	}
	return record;
}

// GH-26

function writeAReview_onClick(){
	var cmCategoryId = getCmCategoryId();
	cmCreateConversionEventTag('Write a Review','1', cmCategoryId, '5','PRODUCTDETAIL-_-'+cmCategoryId);
}

function writeAReviewCompleted(item_num, categoryId){
	cmCreateConversionEventTag("Write a Review", "2", "User Reviews", "20", 'Write a Review-_-'+categoryId);
}

function readAllReviews_onClick(){
	var cmCategoryId = getCmCategoryId();
	cmCreateConversionEventTag('Read All Reviews','2', cmCategoryId, '10','PRODUCTDETAIL-_-'+cmCategoryId);
}

function helpfulReview_onClick(){
	var cmCategoryId = getCmCategoryId();
	cmCreateConversionEventTag('Helpful Review','2', cmCategoryId, '5','PRODUCTDETAIL-_-'+cmCategoryId);
}

function unhelpfulReview_onClick(){
	var cmCategoryId = getCmCategoryId();
	cmCreateConversionEventTag('Unhelpful Review','2', cmCategoryId, '5','PRODUCTDETAIL-_-'+cmCategoryId);
}

function inappropriateReview_onClick(){
	var cmCategoryId = getCmCategoryId();
	cmCreateConversionEventTag('Inappropriate Review','2', cmCategoryId, '5','PRODUCTDETAIL-_-'+cmCategoryId);
}

function sharedReview_onClick(){
	var cmCategoryId = getCmCategoryId();
	cmCreateConversionEventTag('Shared Review','2', cmCategoryId, '5','PRODUCTDETAIL-_-'+cmCategoryId);
}

/**
* Created By:  Waseem Omar
* Description: To call the original cmCreatePageElementTag after trimming both
*  			   elementID and elementCategory to 50 characters per GH-804.
**/
function cmCreatePageElementTagAndTrimParameters(elementID, elementCategory, attributes) {
	var subElementID = elementID;
	if(elementID != null) {
		if (elementID.length > 50) {
			subElementID = elementID.substring(0, 49);
			subElementID = subElementID + '~';
		}
	}
	var subElementCategory = elementCategory;
	if(elementCategory != null) {
		if (elementCategory.length > 50) {
			subElementCategory = elementCategory.substring(0, 49);
			subElementCategory = subElementCategory + '~';
		}
	}
	cmCreatePageElementTag(subElementID, subElementCategory, attributes);
}


/**
* Created By:  Ja'far Shunnar - 08/12/11
* Description: Created to insert an explore attribute in the specified position 
				within the explore attributes string. For example, If we want 
				to put a value of "USD" as the 8th attribute, then
				attribute = USD, and position = 8. Position must always be > 1.
				This method cannot be used to MODIFY the value of an existing attribute,
				but to insert a brand new attribute value at the specified position.
**/

function insertExploreAttribute (fullExploreAttributesString, attribute, position) {

	var indexToStart = -1;

	// get the index of the delimiter preceeding the target position

	for (var i = 0; i < position - 1; i++) {		
		indexToStart = fullExploreAttributesString.indexOf(ATTRIBUTE_DELIMETER, indexToStart + 1);		
	}
	
	// Move the cursor 3 characters to fully include the preceeding delimter -_-	
	var lastIndexForFirstSub = indexToStart + 3;
	
	// Handle the case when we want to insert a value for the first attribute (position = 1).
	if (indexToStart == -1) {
		lastIndexForFirstSub = 0;
	}
	
	var firstSub = fullExploreAttributesString.substring (0, lastIndexForFirstSub);	
	firstSub = firstSub + attribute;
	
	var secondSub = fullExploreAttributesString.substring (lastIndexForFirstSub, fullExploreAttributesString.length);	
	
	return firstSub + secondSub;
}

function cm_getCMProductAttributes() {
	return cmAttribute;
}

