var localHost = document.domain;
var mainDomain = localHost.substring(4);

//Special Domains
var specialDomains = new Array(
		'xunlei.39.net',
		'xhby.39.net',
		'iqilu.39.net',
		'dajiang.39.net'
	);

for (var i = 0; i < specialDomains.length; i++) {
    eval('var pattern = /.+\\.' + specialDomains[i] + '/gi;');
    if (pattern.test(localHost)) {
        mainDomain = specialDomains[i];
        break;
    }
}

//JSON request url
var configuri = 'templates/' + mainDomain + '/displayconfig.js';

$(document).ready(function() {
    $.getJSON(configuri, function(json) {
        document.title = json.host_name + '_' + document.title;
        $('body').prepend(createIframe('iframe_header', json.header_url, json.header_height, json.header_width));
        $('body').append(createIframe('iframe_footer', json.footer_url, json.footer_height, json.footer_width));
        $('span#WebSiteNameCN').text(json.host_name);

        var replaceDomains = json.replace_domain;
        adjustLinks($('div#DiseaseDetail'), replaceDomains);
    });
});

function createIframe(id, url, height, width) {
    var html = '<iframe id="' + id
                      + '" src="' + url
                      + '" height="' + height
                      + '"  width="' + width
                      + '" frameBorder="0" scrolling="no" marginwidth="0" marginheight="0" border="0"></iframe>';
    return html;
}

function adjustLinks($obj, replaceDomains) {
    $allLinks = $obj.find('a,area');
    $allLinks.each(function() {
        var currentHost = $(this)[0].hostname;
        var currentHref = $(this).attr('href');
        if (currentHost != localHost && currentHost != '') {

            if (replaceDomains[currentHost] != undefined) {

                var replaceHref = '';
                eval('var pattern = /\\/([\\da-f]{5})\\.html$/i;');

                if (pattern.test(currentHref)) {
                    replaceHref = currentHref.match(pattern)[1];
                    if (replaceHref) {
                        replaceHref = 'http://' + replaceDomains[currentHost] + '/Detail.aspx?bid=' + parseInt(replaceHref, 16);
                    }
                    else {
                        eval('var rExp = /' + currentHost + '/gi;');   // Create RegExp
                        replaceHref = currentHref.replace(rExp, replaceDomains[currentHost]);
                    }

                    $(this).attr('href', replaceHref);
                }
                else {
                    $(this).removeAttr('href');
                }
            }
            else {
                $(this).removeAttr('href');
            }
        }
    });
}
