/*
// This function creates a proper geotargeted iTunes affiliate link with all the properties required for
// affiliate tracking. The links created are so called deep links and they begin with http
// so they should not be used inside apps as-is because it will first launch the browser
// and then the App Store app. Refer to Apple documentation at 
// http://www.apple.com/itunes/affiliates/resources/documentation/linking-to-the-itunes-music-store.html#apps
// to find out how to properly support linking within apps.
// 
// To use this function you must add the following import to your header (add script tags around it):
// src="http://www.google.com/jsapi" type="text/javascript"
//
// appLinkHref parameter is a deep link to the app in app store. Use isAppStoreLink and cleanAppStoreLink
// to check and clean the link of all unnecessary cruft before calling this function.
//
// If you copy the link from the App Store, you get something like:
// http://itunes.apple.com/us/app/bobthebubble/id366796967?mt=8

// Remove 'us' from the link and you'll get the correct link to use with the function:
// http://itunes.apple.com/app/bobthebubble/id366796967?mt=8
//
// Note that this function returns just the href of an anchor tag without the anchor tags.
//
// Copyright 2011 Mikko Martikainen
*/
function constructAppStoreAffiliateLinkHref(appLinkHref) {

    // Put your affiliate program ids here.
	var linkshareAffiliateToken = '1WeaSXlPPmc';
	var tradedoublerProgramId = '23708';
	var dgmAffiliateToken = '';

	var affiliateLinkPart1;
	var affiliateLinkPart2 = '" rel="self">';
	var itunesLink = appLinkHref;

  	if (google.loader.ClientLocation &&
        google.loader.ClientLocation.address.country_code) {
		var country = google.loader.ClientLocation.address.country_code.toLowerCase();
		itunesLink = appLinkHref.replace('itunes.apple.com/', 'itunes.apple.com/'.concat(country, '/'));
		// use linkshare for USA, Canada and Japan
       	if (country == 'us' || country == 'ca' || country == 'jp') {
            if (linkshareAffiliateToken == '') {
                return (itunesLink);
            }
        affiliateLinkPart1 = 'http://click.linksynergy.com/fs-bin/click?id='.concat(linkshareAffiliateToken, '&subid=&offerid=146261.1&type=10&tmpid=3909&RD_PARM1=');
        itunesLink = itunesLink.concat('&partnerId=30');
		itunesLink = encodeURIComponent(itunesLink);

		// Use DGM for Australia and New Zealand
        } else if (country == 'au' || country == 'nz') {
            if (dgmAffiliateToken == '') {
                return (itunesLink);
            }

		// Use TradeDoubler for Europe
        } else {
            if (tradedoublerProgramId == '') {
//                return ('<a href="'.concat(itunesLink, '" rel="self">'));
                return (itunesLink);
            }
            var tradedoublerWebsiteId = 1952454; // put your site id here
            affiliateLinkPart1 = 'http://clk.tradedoubler.com/click?p='.concat(tradedoublerProgramId, '&a=', tradedoublerWebsiteId, '&url=');
            itunesLink = itunesLink.concat('&partnerId=11703474');

        }

		// percent-encode the itunes link as per Apple's recommendation
		itunesLink = encodeURIComponent(itunesLink);
		return (affiliateLinkPart1.concat(itunesLink));
  	}else{
  	}
    
    // In case geotargeting fails, return plain app store link
    return (itunesLink);

}

/*
// Modifies all links to the App Store within a page to point to the geotargeted
// affiliate program. Place this function call in window.onload
*/
function modifyAppStoreLinks() {
    var i;
    var l = document.links.length;
    for (i=0;i<l;i++) {
        var linkHref = document.links[i].href;
        if (isAppStoreLink(linkHref)) {
        	var a= linkHref;
            linkHref = cleanAppStoreLink(linkHref);
            var b= linkHref;
            document.links[i].href = constructAppStoreAffiliateLinkHref(linkHref);
            var c= document.links[i].href;
                        //alert("A "+a+"\n "+"B "+b+"\n "+"C "+c+"\n ");

        }
    }
}

/*
// Tries to identify is a link href is pointing to the app store.
*/
function isAppStoreLink(linkHref) {
    var appIndex = linkHref.indexOf('/app/', 0);
    var hostIndex = linkHref.indexOf('http://itunes.apple.com', 0);
    if ((appIndex > -1) && (hostIndex > -1) && (hostIndex < appIndex)) {
        return (true);
    } else {
        return (false);
    }
}

/*
// Tries to clean the link href from any unnecessary cruft. Returns
// a link to the app store without country code in the href.
*/
function cleanAppStoreLink(linkHref) {
    var cleanedLinkHref = linkHref;
    if (linkHref.indexOf("http://itunes.apple.com/app/") == -1) {
        // remove any possible cruft from the beginning of the link
        cleanedLinkHref = linkHref.slice(linkHref.indexOf("http://itunes.apple.com/"));
        // get the part of the string after http://itunes.apple.com/
        var tmpString = cleanedLinkHref.slice(24);
        // country codes are 2 chars
        if (tmpString.split("/", 1)[0].length == 2) {
            // remove the 2 country code chars and the following /
            tmpString = tmpString.slice(3);
        }
        cleanedLinkHref = cleanedLinkHref.substr(0, 24).concat(tmpString);
    }
    return (cleanedLinkHref);
}
