// get param value from url
function getParam(name) {
    var match = new RegExp(name + "=([^&]+)","i").exec(location.search);
    if (match==null)
        match = new RegExp(name + "=(.+)","i").exec(location.search);
    if (match==null)
        return null;
    match = match + "";
    result = match.split(",");
    if(result != '')
        result = result[1];
    return result; //result[1];
}
/*                                
* Handle banned domain by redirecting to somewhere else.
*/
function redirect() {
window.location = "http://www.simplesearching.com";
}


function setGoogleRequest(isResultPage,isSecondCall,isD2R){
     if(isResultPage){
         // result page
           if (isSecondCall){
               google_afd_request = google_afs_request;
           }else{
               google_afd_request = google_afd_no_ads_request;
           }
     }else{
         // lander page
         if(isD2R =='true'){
		if (isSecondCall){
			google_afd_request = google_afd_ads_only_request;
		}else{
			google_afd_request = google_afd_no_ads_no_token_request;
		}
         } else{
            google_afd_request =  google_afd_no_ads_no_token_request;
         }
     }
}

function checkStatusUpdate(google_afd_response){
    var old_status = "clean";
    var new_status = "clean";
    if (isGoogleAdult && isGoogleAdult == "true"){
        old_status = "adult";
    }

    if (google_afd_response.faillisted) {
        new_status = "faillisted";
    }else if (google_afd_response.adult == "true"){
        new_status = "adult";
    }

    if(esbGoogleStatusUpdate && esbGoogleStatusUpdate == "true" && old_status != new_status){
        updateStatus(new_status);
    }

}

function google_afd_ad_request_done(google_afd_response) {

    //////////////////////////////////////////////////////////////////////////////////
    ///
    /// domain feed status update  (do it only for landing page on teh first afd call)
    ///
    //////////////////////////////////////////////////////////////////////////////////

    // check status if google response came as faillisted or if status came as not faillisted and this is the first afd call on landing page
    if (google_afd_response.faillisted || (isLander=="true" && google_afd_response.client && (google_afd_response.client == googleAFDNoAdClientId))){
        checkStatusUpdate(google_afd_response);
    }

    if (google_afd_response.faillisted) {
        redirect();
        return;
    }

    if (typeof(google_afd_response.client) == "undefined")
        return;

    if (google_afd_response.client == 'ca-dp-namemedia-rs' || google_afd_response.client == 'ca-dp-namemedia_adult-rs') {
        //this is AFD relateds only
        googleAFDResponse = google_afd_response;
    }

    if (typeof(google_afd_response.token) == "undefined"){
        //this is AFS call
        adsList = google_afd_response.ads;
    }

    if (google_afd_response.ads && google_afd_response.ads.length > 0) {

            listAds = google_afd_response.ads;

            // for event trackign check if repeat ads were returned
            if (feed == 'AS' && repeatAdsEnabled && getSponsoredListingsCount(listAds,'Bottom') > 0){
                 repeat_ads_returned = true;
            } else{
                 repeat_ads_returned = false;
            }
            tr_action = tr_action + (repeat_ads_returned ? "Repeat":"NoRepeat");


             // Format ads.
            if (google_afd_response.ads && google_afd_response.ads.length > 0) {
                var google_ads = google_afd_response.ads;
                for (var i = 0; i < google_ads.length; i++) {
                
                                 
                    ads += '<br/><a  class="adTopLink" href="' + google_ads[i].url + '"' +
                       'onclick="return process_ad(\'' + google_ads[i].url + '\',\'' + google_ads[i].visible_url + '\',\'' + google_ads[i].n + '\',\'' + encodeURIComponent(stripHTML(google_ads[i].line1)) + '\',\'' + encodeURIComponent(stripHTML(google_ads[i].line2)) + '\',\'' + google_ads[i].type + '\');"' +
                       'onmouseout="window.status=\'\'" ' + 'onmouseover="window.status=\'go to ' + google_ads[i].visible_url + '\';return true;" ' +
                       'style="text-decoration:none" target="_blank" rel="nofollow">' +
                       '<span  class="adText" style="text-decoration:underline">' +
                       '<b>' + google_ads[i].line1 + '</b><br></span>' +
                       '<span style="color:#000000" >' + google_ads[i].line2;
                    if (google_ads[i].line3 != undefined && google_ads[i].line3 != '') {
                        ads += '<br>' + google_ads[i].line3;
                    }
                    ads += '<br></span><span style="color:#008000" class="adBottomLink" rel="nofollow">' + google_ads[i].visible_url + '</span></a><br/>';
                }
            }
    } else if (google_afd_response.client != googleAFDNoAdClientId){
        // this is either AFS or AFD ads client id, therefore we expect ads
         tr_action = tr_action + 'NoAds';
    }


        // Format popular categories.
        if (google_afd_response.categories && google_afd_response.categories.length > 0) {

          listPopular = google_afd_response.categories;
            var google_categories = google_afd_response.categories;
            for (var i = 0; i < google_categories.length; i++) {
                popularCategories += '<a href="/?domain_name=' + google_afd_response.request.s +
                                     '&q=' + encodeURIComponent(google_categories[i].term) +
                                     '&token=' + google_categories[i].token + '">' + google_categories[i].term + '</a><br/>';
            }
        }

        // Format related searches.
        if (google_afd_response.link_units && google_afd_response.link_units.length > 0) {

            listRelated = google_afd_response.link_units;

            var google_link_units = google_afd_response.link_units;
            for (var i = 0; i < google_link_units.length; i++) {
                relatedSearches += '<a href="' + buildRelatedSearchUrl(rootPath, google_link_units[i].term, google_link_units[i].token) + '">' +
                                google_link_units[i].term + '</a>';
            }
        }
    }


function getRelatedCount(userDefinedRelateds,googleAFDResponse,max_count) {
    // userDefinedRelateds and  googleAFDResponse should be drfined earlier
    var count = 0;
    var useUserDefinedRelateds = (userDefinedRelateds.length > 0);
    var google_relateds = googleAFDResponse.link_units;

    if (max_count && max_count > 0) {
        if (useUserDefinedRelateds) {
            count = Math.min(userDefinedRelateds.length, max_count);
        } else if (google_relateds && google_relateds.length > 0) {
            count = Math.min(google_relateds.length, max_count);
        }
    } else {   
        if (useUserDefinedRelateds) {
            count = userDefinedRelateds.length;
        } else if (google_relateds && google_relateds.length > 0) {
            count = google_relateds.length;
        }
    }
    return count;
}


function getRelated(userDefinedRelateds,googleAFDResponse,max_count,tag_start,tag_end,maxChar,start_count,end_count,reverse){
    var count = getRelatedCount(userDefinedRelateds,googleAFDResponse,max_count);
    var relatedSearches = '';
    //var relatedSearches_reversed = '';
    var google_relateds = googleAFDResponse.link_units;
    var useUserDefinedRelateds = (userDefinedRelateds.length > 0? true : false);
    var related_length = 0;
    var customRelatedToken = (googleAFDResponse.token ? googleAFDResponse.token : '');

    if (start_count){
        // alert('start_count');
    }  else {
        // alert('no start_count');
        start_count = 0
    }

     if (end_count == null){
         //alert('no end_count');
        end_count = count - 1;
    }  else {
     	//  alert('end_count');
        end_count = Math.min(end_count ,count-1);
    }

    if (!reverse){
    for (var i = start_count; i <= end_count; i++) {
         var display = useUserDefinedRelateds ? (userDefinedRelateds[i].display) : (google_relateds[i].term);
        var url =  useUserDefinedRelateds ?  userDefinedRelateds[i].url + customRelatedToken :
                    buildRelatedSearchUrl(rootPath, google_relateds[i].term, google_relateds[i].token);
         related_length = related_length + display.length;
         if ((display).length>0){ // make sure there is actual data
             if (!maxChar || related_length < maxChar){ // make sure haven't gone over max length
               relatedSearches += tag_start + '<a href="' + url + '">' + display + '</a>' + tag_end;
             }
         }
     }
     } else {// reverse
         for (var i = count - start_count - 1 ; i > count - end_count; i--) {
         var display = useUserDefinedRelateds ? (userDefinedRelateds[i].display) : (google_relateds[i].term);
             var url =  useUserDefinedRelateds ?  userDefinedRelateds[i].url + customRelatedToken :
                    buildRelatedSearchUrl(rootPath, google_relateds[i].term, google_relateds[i].token);
         related_length = related_length + display.length;
         if ((display).length>0){ // make sure there is actual data
             if (!maxChar || related_length < maxChar){ // make sure haven't gone over max length
               relatedSearches += tag_start + '<a href="' + url + '">' + display + '</a>' + tag_end;
             }
         }
     }
     }

    return   relatedSearches;

   
}

function getActualRelateds(userDefinedRelateds, googleAFDResponse){
	var google_relateds = googleAFDResponse.link_units;
    var customRelatedToken = (googleAFDResponse.token ? googleAFDResponse.token : '');
	var actualRelateds = new Array();
	if (userDefinedRelateds.length > 0) {
		for (var i = 0; i < userDefinedRelateds.length; i ++) {
			actualRelateds[i] = {url: userDefinedRelateds[i].url + customRelatedToken, display: userDefinedRelateds[i].display};
		}
	} else {
		for (var i = 0; i < google_relateds.length; i ++) {
			actualRelateds[i] = {url: buildRelatedSearchUrl(rootPath, google_relateds[i].term, google_relateds[i].token), display: google_relateds[i].term};    
		}
	}
	return actualRelateds;
}

function getRelatedKeywords(userDefinedRelateds, googleAFDResponse, start_count, end_count) {
    var count = getRelatedCount(userDefinedRelateds, googleAFDResponse);
    var kwds = '';
    var seperator = ', ';
    var useUserDefinedRelateds = (userDefinedRelateds.length > 0? true : false);
    var google_relateds = googleAFDResponse.link_units;

    if (start_count){
        // alert('start_count');
    }  else {
        // alert('no start_count');
        start_count = 0
    }

     if (end_count){
       //  alert('end_count');
        end_count = Math.min(end_count,count);
    }  else {
         //alert('no end_count');
        end_count = count;
    }

    if (useUserDefinedRelateds) {
        for(var i = start_count; (i < userDefinedRelateds.length) && (i < end_count); i++) {
            if (kwds != '') kwds = kwds + seperator;
            kwds =  kwds + userDefinedRelateds[i].display;
        }
    } else {
        for(var i = start_count; (i < google_relateds.length) && (i < end_count); i++) {
            if (kwds != '') kwds = kwds + seperator;
            kwds = kwds + google_relateds[i].term;
        }        
    }
    return kwds;
}

  function getSponsoredListings(listAds,position){
      var ads = '';
      if (listAds && listAds.length > 0) {
          for (var i = 0; i < listAds.length; i++) {
              if (!position || (position == 'Top' && listAds[i].position == 'Top') || (position == 'Bottom' && !listAds[i].position)){
                  // click tracking
                  var action = tr_action + '_' + (position && (position == 'Bottom') ? 'BottomSP' : 'TopSP');
                  var trackEventStr = "trackEvent('" + tr_categoryClick + "','" + action + "','" + tr_label  + "'," + listAds[i].n + ");";

                  var line2 = listAds[i].line2 + (listAds[i].line3 ? ' ' + listAds[i].line3 : '');
                  ads +=  '<li>' +
                       '<a  class="adTopLink" href="' + listAds[i].url + '"' +
                       'onclick="' + trackEventStr + 'process_ad(\'' + listAds[i].url + '\',\'' + listAds[i].visible_url + '\',\'' + listAds[i].n + '\',\'' + encodeURIComponent(stripHTML(listAds[i].line1)) + '\',\'' + encodeURIComponent(stripHTML(line2)) + '\',\'' + listAds[i].type + '\');"' +
                       'onmouseout="window.status=\'\'" ' + 'onmouseover="window.status=\'go to ' + listAds[i].visible_url + '\';return true;" ' +
                       'target="_blank" rel="nofollow" escapeXml="false">' + listAds[i].line1 + '</a>' +
                       '<br />' +
                       '<span  class="adText"  escapeXml="false">' + line2 +'</span>' +
                       '<br />' +
                        buildSellerRating(listAds[i]) +
                        '<a  class="adBottomLink" href="' + listAds[i].url + '"' +
                       'onclick="' + trackEventStr + 'process_ad(\'' + listAds[i].url + '\',\'' + listAds[i].visible_url + '\',\'' + listAds[i].n + '\',\'' + encodeURIComponent(stripHTML(listAds[i].line1)) + '\',\'' + encodeURIComponent(stripHTML(line2)) + '\',\'' + listAds[i].type + '\');"' +
                       'onmouseout="window.status=\'\'" ' + 'onmouseover="window.status=\'go to ' + listAds[i].visible_url + '\';return true;" ' +
                       'target="_blank" rel="nofollow" escapeXml="false">' +    listAds[i].visible_url + '</a>' +
                        buildSiteLinks(listAds[i], trackEventStr) +
                        '</li>';
              }
          }
      }

      return ads;
 }

// returns the number of SP (sponsored listings) returned by position
// position - not passed --> returns all SP
// position - 'Top'      --> returns all SP with position property set to 'Top'; this happens when repeat ads are requested
// position - 'Bottom'   --> returns all SP with no position set
 function getSponsoredListingsCount(listAds,position){
      var cnt = 0;
      if (listAds && listAds.length > 0) {
          for (var i = 0; i < listAds.length; i++) {
              if (!position || (position == 'Top' && listAds[i].position == 'Top') || (position == 'Bottom' && !listAds[i].position)){
                  cnt++;
              }
          }
      }
      return cnt;
 }

  function getPopular(listPopular,categ_tag_start,categ_tag_end,categ_tag_start_last,categ_title_tag_start,categ_title_tag_end,subcateg_tag_start,subcateg_tag_end,start_count,end_count){

    var categoriesString = '';
    var customRelatedToken = (googleAFDResponse.token ? googleAFDResponse.token : '');

    if (listPopular && listPopular.length > 0) {

       if (!start_count){
        //  alert('no start_count');
         start_count = 0
        }
        if (end_count){
        //  alert('end_count');
            end_count = Math.min(end_count ,listPopular.length);
        }  else {
           //  alert('no end_count');
            end_count = listPopular.length;
        }
       // alert('start_count' + start_count + ' *** end_count' + end_count);

       for (var i = start_count; i < end_count; i++) {
        // categories
         var title = categ_title_tag_start + listPopular[i].term + categ_title_tag_end;

         if (categ_tag_start_last && categ_tag_start_last.length > 0  && i < end_count - 1)
            categoriesString += categ_tag_start+ title;
         else
            categoriesString += categ_tag_start_last + title;

         if (listPopular[i].subcategories && (listPopular[i].subcategories).length > 0) {
             var subCategories = listPopular[i].subcategories;
             var subCategoriesString = subcateg_tag_start;
             var j_count  = (listPopular[i].subcategories).length - 1;
             for (var j = 0; j <= j_count; j++) {
                 // sub categories
                 var token = (subCategories[j].token == 'thetoken'?customRelatedToken:subCategories[j].token);
                 subCategoriesString +=  '<a href="' + buildRelatedSearchUrl(rootPath , subCategories[j].term, token) + '">' +
                                    subCategories[j].term + '</a>' ;
                 if (j != j_count){
                          subCategoriesString += ', ';
                 }
             }
             subCategoriesString += subcateg_tag_end;
             categoriesString += subCategoriesString;
         }
         categoriesString += categ_tag_end;
       }
     }
     return categoriesString;
    }


    function getLinkString(part1,thetoken,part3){
           thetoken = googleAFDResponse.token;
            return part1 + thetoken + part3;
    }


    function process_ad(url, visibleUrl, rank, line1, line2, type)    {
   // alert('doing ajax');
    //ajax call to capture click
   
    var href = rootPath +  "?feed=" + feed + "&template=" + template +  "&rank=" + rank + "&keyword=" +  strKeyword +  "&d=" +  encodeURIComponent(visibleUrl) + "&rid=" + encodeURIComponent(url);
    if (s_token && s_token != ''){
        href = href + "&s_token=" + s_token;
    }
    //alert('doing ajax: ' + href);
    $.ajax({
          type: "GET",
          async: true,
          url: href,
          data: {isGoogleJSFeed: 'yes', line1: line1, line2: line2, type: type},//"isGoogleJSFeed=yes&line1=irina",  
          dataType: 'json',
          contentType: "application/json; charset=utf-8",
          success: function(){
              //alert('Ajax call to capture a click is succeeded');
          }
        });
     return true;

    }

function buildRelatedSearchUrl(rootPath, term, token) {
    var relatedSearchUrl = rootPath
            + encodeURIComponent(term.split(' ').join('-')) + '.html'
            + '?afdt=' + token;
    if (s_token && s_token != ''){
        relatedSearchUrl = relatedSearchUrl + '&s_token=' + s_token;
    }
    return relatedSearchUrl;
}


function stripHTML(string) { 
    return string.replace(/<(.|\n)*?>/g, ''); 
}


function buildSellerRating(ad) {
    var sellerRatings = '';
    var review = '';
    var rating = '';
    var linkStart = '';
    var linkEnd = '';
    if (ad.seller_ratings) {
        if (ad.seller_ratings.text){
            sellerRatings = ad.seller_ratings.text;
        }
        if (ad.seller_ratings.rating){
            rating = '<img src="' + imagePath + '/images/stars_graphic_' + ad.seller_ratings.rating + '.png"/>';
            sellerRatings = sellerRatings.replace('{{RATING}}',rating);
        }

        if (ad.seller_ratings.source_url){
            linkStart =  ' <a class="adSellerRatingLink" href="' + ad.seller_ratings.source_url + '" target="_blank">';
            linkEnd =  ' </a>';
            sellerRatings = sellerRatings.replace('{{LINK_START}}',linkStart);
            sellerRatings = sellerRatings.replace('{{LINK_END}}',linkEnd);
        }

        sellerRatings += '<br/>';
    }
    return sellerRatings;
}

function buildSiteLinks(ad, trackEvent) {
    var siteLinks = '';
    var trackEventStr = (trackEvent? trackEvent : '');
    if (ad.sitelinks && ad.sitelinks.length > 0) {
        siteLinks = '<div style="display:float;">';
        siteLinks += '<ul id="siteLinks">';
        for (var i = 0; i < ad.sitelinks.length; i++) {
            siteLinks += '<li>';
            siteLinks += '<a  class="adSiteLink" href="' + ad.sitelinks[i].url + '"' +
                       'onclick="' + trackEventStr + 'process_ad(\'' + ad.sitelinks[i].url + '\',\'' + ad.visible_url + '\',\'' + ad.n + '\',\'' + encodeURIComponent(stripHTML(ad.line1)) + '\',\'' + encodeURIComponent(stripHTML(ad.line2)) + '\',\'' + ad.type + '\');"' +
                       'onmouseout="window.status=\'\'" ' + 'onmouseover="window.status=\'go to ' + ad.visible_url + '\';return true;" ' +
                       'target="_blank" rel="nofollow">' + ad.sitelinks[i].link_text + '</a>';
            siteLinks += '</li>';
        }
        siteLinks += '</ul>';
        siteLinks += '</div><div style="clear:both"></div>';
    }
    return siteLinks;
}

function updateStatus(status){

    ///////////////////////////////////////////
    //http://foo.com/dfsu?fd=1&amp;s=faillisted
    ///////////////////////////////////////////

    var feedId = 1; //google

    //var href = rootPath +  "dfsu?f=" + feedId + "&s=" + status;
    var href = rootPath +  "dfsu";

    $.ajax({
            type: 'POST',
            url: href,
            data: '{"feedProviderId":' + feedId + ',"feedStatus":"' + status + '"}',
            dataType: 'json',
            contentType: "application/json; charset=utf-8"/*,
            success: function(data) {
            }*/
           });

}

 function trimString(inputString, length){

    var inputStringLength = inputString.length;
    var outputString = '';
    if (!length || inputStringLength<=length) {
        outputString = inputString;
    } else{
        outputString =  inputString.substring(0,inputString.lastIndexOf(" ",length-1)) + ' ...';
    }
    return outputString;
}

function trackEvent(categoty,action,label,value){
    _gaq.push(['cl._trackEvent', categoty,action,label,value]);

}


