tm_virtual_host = 'api.tmarque.com';
﻿var tm_jump_url = "#search";
if (tm_is_defined("tm_application_id") && tm_application_id!="" && tm_application_id!=null) tm_jump_url = tm_jump_url + "-appID=" + tm_application_id;
if (location.hash.indexOf("#") == -1) location.replace(location + tm_jump_url); //initial stage

// We only support IE 8 running in IE 8 mode in this API.  Ensure your page either has meta tag inside head
// <meta http-equiv="X-UA-Compatible" content="IE=edge" /> or else is rendering in IE 8 mode
//<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

//onload = function() { // Only run if we detect IE 8 browser
//alert(document.getElementsByTagName("META").item(0).content);
//"IE=edge" or "IE=EmulateIE8"
//Should check each tag and generate error if any other values have been set (IE=EmulateIE7, etc)
//}; 

function tm_is_defined(variable) {
    return (typeof (window[variable]) != "undefined");
}

function tm_location_hash() {
    return (top.location.href.split("#")[1] || "")
}

// Need to provide an alert if we detect IE 8 running in IE 7 mode due to navigation issues.
// TODO Fix if browser jumps right to end or start (back/forward) 
// tm_trademark is now set below
var tm_application_id = ""; // we are setting this below
var tm_hash = tm_location_hash(); //location.hash.substring(1); //current browser hash

if (!tm_is_defined("tm_virtual_host")) tm_virtual_host = "api.dev.remarqueble.com";
tm_partner = tm_is_defined("tm_partner") ? tm_partner + "." : "";
if (!tm_is_defined("tm_base_uri")) tm_base_uri = "http://" + tm_partner + tm_virtual_host + "/";
if (!tm_is_defined("tm_frame_width")) tm_frame_width = 1000;
if (!tm_is_defined("tm_frame_height")) tm_frame_height = 740;
//if (!tm_is_defined("tm_application_id")) tm_application_id = "";
if (!tm_is_defined("tm_curvy_corners_script")) tm_curvy_corners_script = "";
if (!tm_is_defined("tm_payment_url")) tm_payment_url = "";
if (!tm_is_defined("tm_event_url")) tm_event_url = "";
if (!tm_is_defined("tm_payment_account")) tm_payment_account = "";
if (!tm_is_defined("tm_css_font_family")) tm_css_font_family = "";
if (!tm_is_defined("tm_css_url")) tm_css_url = "";
if (!tm_is_defined("tm_runtime_mode")) tm_runtime_mode = ""; // default is production
if (!tm_is_defined("tm_payment_header_image_url")) tm_payment_header_image_url = "";
if (!tm_is_defined("tm_tc_url")) tm_tc_url = "";
if (!tm_is_defined("tm_tc_mode")) tm_tc_mode = "";
if (!tm_is_defined("tm_css_mode")) tm_css_mode = "";
if (!tm_is_defined("tm_css_whitespace_default")) tm_css_whitespace_default = "";
if (!tm_is_defined("tm_header_mode")) tm_header_mode = "";
if (!tm_is_defined("tm_tax_name")) tm_tax_name = "";
if (!tm_is_defined("tm_currency_code")) tm_currency_code = "";
if (!tm_is_defined("tm_currency_symbol")) tm_currency_symbol = "";
if (!tm_is_defined("tm_app_fee_first_class")) tm_app_fee_first_class = "";
if (!tm_is_defined("tm_app_fee_extra_class")) tm_app_fee_extra_class = "";
if (!tm_is_defined("tm_reg_fee_first_class")) tm_reg_fee_first_class = "";
if (!tm_is_defined("tm_reg_fee_extra_class")) tm_reg_fee_extra_class = "";
if (!tm_is_defined("tm_search_mode")) tm_search_mode = "";
if (!tm_is_defined("tm_start_stage")) tm_start_stage = "";
if (!tm_is_defined("tm_trademark")) tm_trademark = "";
if (!tm_is_defined("tm_trademark_type")) tm_trademark_type = "";
if (!tm_is_defined("tm_trademark_country_code")) tm_trademark_country_code = "";
if (!tm_is_defined("tm_search_text")) tm_search_text = "";
if (!tm_is_defined("tm_save_app_mode")) tm_save_app_mode = "";
if (!tm_is_defined("tm_app_applicant_type")) tm_app_applicant_type = "";
if (!tm_is_defined("tm_app_company_name")) tm_app_company_name = "";
if (!tm_is_defined("tm_app_company_registration")) tm_app_company_registration = "";
if (!tm_is_defined("tm_app_company_country_code")) tm_app_company_country_code = "";
if (!tm_is_defined("tm_app_first_name")) tm_app_first_name = "";
if (!tm_is_defined("tm_app_last_name")) tm_app_last_name = "";
if (!tm_is_defined("tm_app_address_line_1")) tm_app_address_line_1 = "";
if (!tm_is_defined("tm_app_city_suburb")) tm_app_city_suburb = "";
if (!tm_is_defined("tm_app_state_province")) tm_app_state_province = "";
if (!tm_is_defined("tm_app_postal_code")) tm_app_postal_code = "";
if (!tm_is_defined("tm_app_country_code")) tm_app_country_code = "";
if (!tm_is_defined("tm_app_email")) tm_app_email = "";
if (!tm_is_defined("tm_app_phone")) tm_app_phone = "";
if (!tm_is_defined("tm_app_fax")) tm_app_fax = "";

function tm_add_on_load(f) {
    var origonload = window.onload;
    if (typeof (window.onload) != 'function') window.onload = f;
    else { window.onload = function() { if (origonload) origonload(); f(); } }
}

tm_add_on_load(function() { //Disable history
    if (tm_is_defined("Sys")) try { Sys.Application._setState = function() { }; } catch (tm_err) { };
});

if (tm_runtime_mode == "development") {
    //Begin CSS Upload
    tm_css = ""; // CSS to upload to server

    document.write("<div id='tm_css_div' style='visibility:hidden;overflow:hidden;width:0px;height:0px;position:absolute'></div>");

    function tm_css_frameLoaded() {
        //' + encodeURIComponent(escape(data)) + '
        //' + encodeURIComponent(escape(document.location)) + '
        //' + encodeURIComponent(escape(tm_partner)) + '
        window.setTimeout(function() {
            try {
                var tm_frame_document = frames["tm_css_frame"].document;
                if (tm_frame_document != null) {
                    var tm_form = tm_frame_document.getElementById("tm_css_form"); // document.getElementById("tm_css_frame").contentWindow.document.getElementById("mf");
                    tm_frame_document.getElementById("c").value = encodeURIComponent(tm_css);
                    tm_frame_document.getElementById("u").value = encodeURIComponent(document.location);
                    tm_frame_document.getElementById("p").value = encodeURIComponent(tm_partner);
                    tm_form.submit()
                }
                else window.setTimeout(function() { tm_css_frameLoaded(); }, 100);
            }
            catch (err) { }
        }, 1);

        //window.setTimeout(function() {
        //    try {
        //        frames["tm_css_frame"].src = "javascript:'<html></html>'";
        //        frames["tm_css_frame"] = null;
        //        document.getElementById("tm_css_div").innerHTML = "";
        //    } catch (err) { }
        //}, 5000);
        return "";
    }

    function tm_create_css_form() {
        try {
            return 'javascript:"<html><body><form id=tm_css_form name=tm_css_form action=' + tm_base_uri + 'Services/CacheCSS.ashx method=POST><textarea id=c name=c></textarea><textarea id=u name=u></textarea><textarea id=p name=p></textarea></form></body><script language=javascript>parent.tm_css_frameLoaded()</script></html>"'; //+parent.tm_css_frameLoaded();';
        } catch (err) {'javascript:"<html></html>"'; }
    }

    tm_add_on_load(function () {
        try {
            for (tm_x = 0; tm_x < document.styleSheets.length; tm_x++) {
                try {
                    var tm_styleSheet = document.styleSheets[tm_x];
                    var tm_rules = tm_styleSheet.rules ? tm_styleSheet.rules : tm_styleSheet.cssRules;
                    for (tm_y = 0; tm_y < tm_rules.length; tm_y++) {
                        try {
                            var tm_rule = tm_rules[tm_y];
                            if (tm_rule.selectorText.toLowerCase().substring(0, 4) == ".tm_") {
                                var tm_stext = tm_rule.selectorText;
                                // Perform same before and after substitution as server side
                                tm_stext = tm_rule.selectorText.replace(/:before/g, ' .jq_before').replace(/:after/g, ' .jq_after');
                                var tm_cssText = tm_rule.style.cssText;
                                //Note that Safari and Chrome treat '/A ' as '/A' so we need to replace both in the order below.
                                tm_cssText = tm_cssText.replace(/\\A /g, 'ZqZ').replace(/\\a /g, 'ZqZ').replace(/\\A/g, 'ZqZ').replace(/\\a/g, 'ZqZ');
                                tm_css += tm_stext + "{" + tm_cssText + "}";
                            }
                        } catch (err1) { }
                    }
                } catch (err2) { }
            }
        } catch (err3) { }

        try {
            var tm_css_iframe = "<iframe allowtransparency='true' frameborder='0' height='0' hspace='0' id='tm_css_frame' marginheight='0' marginwidth='0' name='tm_css_frame' scrolling='no' src='" + tm_create_css_form() + "' style='left:0;position:relative;top:0' vspace='0' width='0'></iframe>"
            //if (tm_partner.toLowerCase().substring(0, 3) != "tma")
            document.getElementById("tm_css_div").innerHTML = tm_css_iframe;
        } catch (err) { }
    });
} // End of development mode

function tm_qs(qs, key) {
    if (qs.length < 1) return;
    qs = qs.replace(/\+/g, ' ');
    var args = qs.split('&');
    for (var i = 0; i < args.length; i++) {
        var pair = args[i].split('=');
        var name = decodeURIComponent(pair[0]);
        var value = (pair.length == 2) ? decodeURIComponent(pair[1]) : "";
        if (name!=null && name == key) return value;
    }
    return "";
}

//TODO - Need to fix template to replace original data if nothing found
function tm_process_templates(currentStage) {
    if ((templates = document.getElementById('tm_template')) == null) {
        if ((templates = document.getElementById('tmark_template')) == null) { //check this for backwards compatibility
            return;
        }
    }
    var nodes = templates.childNodes;
    for (idx = 0; idx < nodes.length; idx++) {
        if ((node = nodes.item(idx)) == null || (id = node.id) == null || id == "") continue;
        if ((hyphenIndex = id.indexOf('_')) == -1) continue; // Only process elements in correct format
        if ((stage = id.substring(0, hyphenIndex))!=currentStage || id.length <= hyphenIndex + 1) continue;
        var nodeValue = ""; 
        if (node!=null && node.innerHTML!=null) nodeValue = node.innerHTML.replace(/{{trademark}}/g, tm_trademark).replace(/{{application_id}}/g, tm_application_id);
        if ((placeholder = id.substring(hyphenIndex + 1))=='document_title') document.title = nodeValue;
        else if ((placeholderNode = document.getElementById(placeholder)) != null) {
            try {
                placeholderNode.innerHTML = ""; //Set it to clear first in case of exception
                placeholderNode.innerHTML = nodeValue;
            } catch (err) {};
        }       
    }
}

function tm_add_param(param_name, def_value)
{
    return param_name + "=" + (tm_is_defined(param_name) && (eval(param_name) != null) ? encodeURIComponent(eval(param_name)) : encodeURIComponent(def_value));
}

//Might use ordered list, such as ?q=tmarque|field1|field2
//var tm_params =
    //tm_add_param("tm_app_first_name", "") +
    //"&" + tm_add_param("tm_app_last_name", "") +
    //"&" + tm_add_param("tm_app_company_name", "") +
    //"&" + tm_add_param("tm_app_company_number", "") +
    //"&" + tm_add_param("tm_app_company_country_code", "AU") +
    //"&" + tm_add_param("tm_app_address_line1", "") +
    //"&" + tm_add_param("tm_app_suburb", "") +
    //"&" + tm_add_param("tm_app_state", "") +
    //"&" + tm_add_param("tm_app_postal_code", "") +
    //"&" + tm_add_param("tm_app_country_code", "AU") +
    //"&" + tm_add_param("tm_app_email", "") +
    //"&" + tm_add_param("tm_app_phone", "") +
    //"&" + tm_add_param("tm_app_fax", "");
    //"&" + tm_add_param("tm_is_company", "true") +
    //"&" + tm_add_param("tm_redirect_on_success", "") +
    //"&" + tm_add_param("tm_redirect_on_failure", "") +
    //"&" + tm_add_param("tm_redirect_param_app_id", "app_id") +
    //"&" + tm_add_param("tm_redirect_param_status_code", "status_code") + 
    //"&" + tm_add_param("tm_payment_url", "");    

if (tm_runtime_mode != "none") {
    document.write("<div id='tmarkdiv' style='overflow:hidden;width:" + (tm_frame_width - 25) + "px;height:" + (tm_frame_height) + "px;position:relative'>Please wait, loading...</div>");
}

function tm_get_stage() {
    try {
        var stage = tm_location_hash(); //top.location.hash.substring(1);
        var hyphenIndex = stage.indexOf('-');
        var res = (hyphenIndex > -1) ? stage.substring(0, hyphenIndex) : stage;
        if (res == null || res == "") return 'search'; // search is the default
    } catch (Error) { return 'search'; }
}

function tm_qs_add(item, token) {
    //if (token == "t") item = item.replace("'", "%27");
    return (item == "" ? "" : ("&" + token + "=" + encodeURIComponent(item)));
}

function tm_get_url(stage) {
    var pages = {};
    pages['search'] = 'tm/search/';
    pages['specify'] = 'tm/specify/';
    pages['save'] = 'tm/save/';
    pages['submit'] = 'tm/submit/';

    var h = "";
    var hsh = tm_location_hash();  //top.location.hash.substring(1);
    if ((hyphenIndex = hsh.indexOf('-')) > -1 && hsh.length > hyphenIndex + 1) h = "&" + hsh.substring(hyphenIndex + 1)
    return tm_base_uri + pages[stage] + "?purl=" + encodeURIComponent(top.location.href.split('#')[0]) + h
   // + tm_qs_add(tm_application_id, "appID") // problem here - we are including this twice!
    + tm_qs_add(tm_payment_url, "pu")
    + tm_qs_add(tm_event_url, "eu")
    + tm_qs_add(tm_curvy_corners_script, "ccs")
    + tm_qs_add(tm_payment_account, "pa")
    + tm_qs_add(tm_css_font_family, "cff")
    + tm_qs_add(tm_css_url, "cu")
    + tm_qs_add(tm_payment_header_image_url, "phiu")
    + tm_qs_add(tm_tc_url, "tu")
    + tm_qs_add(tm_tc_mode, "tm")
    + tm_qs_add(tm_css_mode, "cm")
    + tm_qs_add(tm_css_whitespace_default, "cwd")     
    + tm_qs_add(tm_runtime_mode, "rm")
    + tm_qs_add(tm_header_mode, "hm")
    + tm_qs_add(tm_tax_name, "tn")
    + tm_qs_add(tm_currency_code, "cc")
    + tm_qs_add(tm_currency_symbol, "cs")
    + tm_qs_add(tm_app_fee_first_class, "affc")
    + tm_qs_add(tm_app_fee_extra_class, "afec")
    + tm_qs_add(tm_reg_fee_first_class, "rffc")
    + tm_qs_add(tm_reg_fee_extra_class, "rfec")
    + tm_qs_add(tm_search_mode, "sm")
    + tm_qs_add(tm_start_stage, "ss")
    + tm_qs_add(tm_trademark, "t")
    + tm_qs_add(tm_trademark_type, "tt")
    + tm_qs_add(tm_trademark_country_code, "tcc")
    + tm_qs_add(tm_search_text, "st")        
    + tm_qs_add(tm_save_app_mode, "sam")        
    + tm_qs_add(tm_app_applicant_type, "aat")
    + tm_qs_add(tm_app_company_name, "acn")
    + tm_qs_add(tm_app_company_registration, "acr")
    + tm_qs_add(tm_app_company_country_code, "accc")    
    + tm_qs_add(tm_app_first_name, "afn")
    + tm_qs_add(tm_app_last_name, "aln")
    + tm_qs_add(tm_app_address_line_1, "aal1")
    + tm_qs_add(tm_app_city_suburb, "acs")
    + tm_qs_add(tm_app_state_province, "asp")
    + tm_qs_add(tm_app_postal_code, "apc")
    + tm_qs_add(tm_app_country_code, "acc")    
    + tm_qs_add(tm_app_email, "ae")
    + tm_qs_add(tm_app_phone, "ap")
    + tm_qs_add(tm_app_fax, "af");             
}

// IE 6 and 7 Specific (need to fix because IE 8 running in IE 7 mode causes this to run which is incorrect)
function tm_ieLessThanV8() {
    if (typeof (document["documentMode"]) != "undefined") return false; // Always return false for IE 8 even if in IE 7 mode.
    return ((verOffset = navigator.userAgent.indexOf("MSIE")) != -1 && navigator.userAgent.substring(verOffset + 5, verOffset + 6) < 8 && navigator.userAgent.substring(verOffset + 6, verOffset + 7) == '.');
}

if (tm_ieLessThanV8()) {
    document.write("<iframe id='historyFrame' src='javascript:\"<html></html>\"' style='visibility:hidden'></iframe>");
}

function tm_onFrameLoaded(hsh) {
    if (tm_location_hash() != hsh) { //if (location.hash != hsh) {
        location.hash = hsh;
        tm_hash = tm_location_hash(); //top.location.hash.substring(1);
        tm_setupFrame();
    }
}

function tm_saveHash(hashValue, pageTitle) {
    var doc = document.getElementById("historyFrame").contentWindow.document;
    doc.open("javascript:'<html></html>'");
    doc.write("<html><head><title>" + pageTitle + "</title><scri" + "pt type=\"text/javascript\">parent.tm_onFrameLoaded('" + (hashValue) + "');</scri" + "pt></head><body></body></html>");
    doc.close();
}
// End IE 6 and 7

var tm_windowLoaded = false;

function tm_updateTemplates(stage) {
    tm_windowLoaded = true;
    tm_process_templates(stage);
    if (tm_ieLessThanV8()) tm_saveHash(tm_location_hash() /*location.hash*/, document.title); // Placed here after dynamic title is set.
    if (stage == 'search') { // If we navigate back to search we need to seutp the default values.
        if (tm_start_stage != 'specify' && tm_start_stage != 'submit') tm_trademark = "";
        tm_application_id = "";
    }
    var desc = "Use args.stage, args.trademark or args.application_id to access fields. \nstage=" + stage + " \ntrademark=" + tm_trademark + " \napplication_id=" + tm_application_id;
    var args = {
        stage: stage,
        trademark: tm_trademark,
        application_id: tm_application_id,
        toString: function() { return desc; }
    };
    if (tm_is_defined("tm_on_stage_loaded")) tm_on_stage_loaded(args);
}

var tm_old_frame = null;

function tm_cleanOldFrame() {
    if (tm_old_frame == null) return;
    tm_old_frame.src = "javascript:'<html></html>'"
    tm_old_frame = null;
};

function tm_setupFrame() {
    var stage = tm_hash;
    if ((hyphenIndex = tm_hash.indexOf('-')) > -1) {
        stage = tm_hash.substring(0, hyphenIndex);
        if (tm_hash.length > hyphenIndex + 1) {
            var params = tm_hash.substring(hyphenIndex + 1)
            if ((mark = tm_qs(params, 'mark')) != null && mark != "") tm_trademark = mark;
            if ((appID = tm_qs(params, 'appID')) != null && appID != "") tm_application_id = appID;
        }
    }
    if (stage == 'search' || stage == 'specify' || stage == 'save' || stage == 'submit') {
        var iframe = "<iframe allowtransparency='true' frameborder='0' height='" + tm_frame_height + "' onload='javascript:tm_cleanOldFrame()' hspace='0' id='tm_main_frame' marginheight='0' marginwidth='0' name='tm_main_frame' scrolling='no' src='" + tm_get_url(stage) + "' style='left:0;position:relative;top:0' vspace='0' width='" + tm_frame_width + "'></iframe>"
        var oldFrame = tm_old_frame = document.getElementById("tm_main_frame");
        // onload does not work on some browsers, so we will also try to clean up after 2 seconds.
        if (oldFrame != null) {
            window.setTimeout(function() {
                if (oldFrame != null) return;
                oldFrame.src = "javascript:'<html></html>'";
                oldFrame = null;
            }, 2000);
        }
        document.getElementById("tmarkdiv").innerHTML = iframe;
        // 3rd party script could lose our window.onload, maybe we need a timer as well?
        //if (tm_windowLoaded == true) tm_updateTemplates(stage);
        //else tm_add_on_load(function() { tm_updateTemplates(stage); });
        tm_updateTemplates(stage);
    }
}

if (tm_runtime_mode != "none") {
    window.setInterval(function () {
        if ((currentHash = tm_location_hash()) /*top.location.hash.substring(1))*/ != tm_hash) {
            tm_hash = currentHash;
            tm_setupFrame(); // top.location.reload()     
        }
    }, 50);

    tm_add_on_load(function() {
        window.setTimeout(function() {
            tm_setupFrame();
        }, 10);
    });
}

