var config = { 
                'DEBUG': true,
                'BRANCH': 'seatmap_testing',
};
if (config['BRANCH'] === 'seatmap_testing') {
    config['SEATMAP_WEBAPI_URL'] = 'https://staging.purchase.tickets.zinomedia.de/seatmap-webapi/api.php';
}
else if (config['BRANCH'] === 'seatmap_main') {
    config['SEATMAP_WEBAPI_URL'] = 'https://zinomedia.de/seatmap_main/seatmap-webapi/api.php';
}

if (!String.prototype.repeat) {
  String.prototype.repeat = function(count) {
    'use strict';
    if (this == null)
      throw new TypeError('can\'t convert ' + this + ' to object');

    var str = '' + this;
    // To convert string to integer.
    count = +count;
    // Check NaN
    if (count != count)
      count = 0;

    if (count < 0)
      throw new RangeError('repeat count must be non-negative');

    if (count == Infinity)
      throw new RangeError('repeat count must be less than infinity');

    count = Math.floor(count);
    if (str.length == 0 || count == 0)
      return '';

    // Ensuring count is a 31-bit integer allows us to heavily optimize the
    // main part. But anyway, most current (August 2014) browsers can't handle
    // strings 1 << 28 chars or longer, so:
    if (str.length * count >= 1 << 28)
      throw new RangeError('repeat count must not overflow maximum string size');

    var maxCount = str.length * count;
    count = Math.floor(Math.log(count) / Math.log(2));
    while (count) {
       str += str;
       count--;
    }
    str += str.substring(0, maxCount - str.length);
    return str;
  }
}

jQuery(document).ready(function() {
    if (config['DEBUG']) console.log(getFuncName('ready'));
    check_inject();
});



function check_inject() {
    if (config['DEBUG']) console.log(getFuncName());
    
    var content = document.getElementsByTagName('html')[0].innerHTML;
    var inputsWithValue = getInputs(content);
    if (config['DEBUG']) console.log(inputsWithValue);
    
    if (!jQuery.isEmptyObject(inputsWithValue)) {
        if (inputsWithValue.hasOwnProperty("trxstate") && inputsWithValue["trxstate"].value == 20) {
            if (config['DEBUG']) console.log("trxstate 20 identified");
            
                var pvo_venue_name = jQuery('.venue span')[0].textContent.toUpperCase();
                var url = config['SEATMAP_WEBAPI_URL'] + '/records/halls?filter=PVO_VENUE_NAME,eq,' + pvo_venue_name + '&include=INJECT';
                if (config['DEBUG']) console.log('Get: ' + url);
                
                var result = jQuery.get(url, function(data) {})
                    .done(function(data) {
                        if (config['DEBUG']) console.log(data);
                        if (data['records'][0]['INJECT']) {
                            if (config['DEBUG']) console.log('Starting inject...');
                            inject_seatmap(inputsWithValue, content);
                        }
                        else {
                            if (config['DEBUG']) console.log('Not injecting.');
                        }
                });
        }
        else if (inputsWithValue.hasOwnProperty("prevtrxstate") && inputsWithValue["prevtrxstate"].value == 30) {
            if (config['DEBUG']) console.log("prevtrxstate 30 identified");
        }
        else {
            if (config['DEBUG']) console.log("No action set: trxstate: " + inputsWithValue["trxstate"].value);
        }
    }
}
function inject_seatmap(inputsWithValue, content) {
    if (config['DEBUG']) console.log(getFuncName('ready'));
    
    manipulateDocument();
    let note = important_note();
    let param = getPosturl(content);
    let request_switch = 'seatmapWorkflow';
    
    if (jQuery('#flash_seat_map_box_id').length) {
        var url = generateUrl(param, inputsWithValue, note, request_switch);
        jQuery("#viewSeatFlashMapButton").unbind();
        jQuery('#viewSeatFlashMapButton').click(function() {
            if (config['BRANCH'] === 'seatmap_testing') {
               window.location.href = 'https://staging.purchase.tickets.zinomedia.de/seatmap-client/index.html?' + "posturl=" + encodeURIComponent(url); 
            }
            else if (config['BRANCH'] === 'seatmap_main') {
                window.location.href = 'https://purchase.tickets.zinomedia.de/seatmap-client?' + "posturl=" + encodeURIComponent(url); 
            }
            else {
                throw new Error('Die: Branch not defined.');
            }
        });
    }
}

function generateUrl(param, inputsWithValue, note, request_switch) {
    if (config['DEBUG']) console.log(getFuncName());

    var url = param[0];
    var event = param[1];
    var holdcode = param[2];
    
    var parameter = '';
    for (var property in inputsWithValue) {
        if (inputsWithValue.hasOwnProperty(property)) {
            parameter = parameter + property + '=' + inputsWithValue[property].value + '&';
        }
    }
    parameter = parameter.substring(0, parameter.length - 1);
    
    url = url + "&holdcode=" + holdcode + "&event=" + event + '&nocache=0&inclpkg=Y&incloffer=Y&inclcartdetails=Y&inclCart=Y&inclvenue=Y' + parameter;
    
    if (typeof note !== 'undefined') {
        url = url + '&note=' + note;
    }
    if (typeof request_switch !== 'undefined') {
        url = url + '&request_switch=' + request_switch;
    }
    
    if (config['DEBUG']) console.log('URI before decode: ' + url);
    
    url = decodeURIComponent(url);
    if (config['DEBUG']) console.log('URI after decode: ' + url);
    
    return url;
}
function getPosturl(content) {
    if (config['DEBUG']) console.log(getFuncName());

    var posturl = content.match(/posturl:"(.+?)"/)[1];
    var event = content.match(/event:"(.+?)"/)[1];
    var holdcode = content.match(/holdcode:"(.+?)"/)[1];
    
    return [posturl, event, holdcode, content];
}
function getInputs(content) {
    if (config['DEBUG']) console.log(getFuncName());

    var inputsWithValue = new Object();
    var data = jQuery.parseHTML(content);
    var checkoutParam = [
        'APPTE', 'age_consent_is_checked', 'agency', 'cancelAndRedirectTrxState', 'cogid', 'coids', 'discount=A=IE', 'discount=A=IV', 'discountdesc=A=IE', 'discountdesc=A=IV', 'discountfees=A=IE', 'discountfees=A=IV', 'discountprice=A=IE', 'discountprice=A=IV', 'dpa_selection', 'etpgcode', 'flashDetected', 'gid', 'hbx_discount_prices', 'hbx_discounts', 'hbx_offered_pg', 'hbx_perf_codes', 'hbx_perf_sub_codes', 'hbx_pids', 'hbx_requested_pg', 'hbx_selected_tixx', 'hbx_upsell_flag', 'request_type', 'invalid_seats', 'inventory_filtering_action', 'inventory_month', 'inventory_year', 'isCapEnabled', 'is_availability_switch_from_map', 'is_ticket_exchange_request', 'ism_map_current_state_json_data', 'jcarousel_auto_off_val', 'listing_type', 'mainEventPID', 'map_coupon_code', 'mlbamsp', 'oid', 'ooids', 'orderkey', 'orgid', 'p_orgid', 'package_pids', 'parent_offer_id', 'pay_pal_token', 'pid', 'prevtrxstate', 'recapToken', 'redeem_voucher_data_event_mapping', 'replay_request', 'request_action', 's_mem_tkt_ren_retrieval', 'schedule', 'secure_trxn_enabled', 'selected_seat_indexes', 'selected_upsell_option', 'supplierCode', 'supplier_code', 'target_name_value', 'target_prev_trxstate', 'target_trxstate', 'target_url', 'timeout_seconds', 'trxstate', 'upsell_selected', 'user_context', 'valid_coupon_code_message'
    ];
    jQuery(data).find('input').each(function() {
        if (this.value !== '') {
            if (checkoutParam.indexOf(this.name)) {
                inputsWithValue[this.name] = this;
            }
        }
    });
    
    return inputsWithValue;
}

function manipulateDocument() {
    if (config['DEBUG']) console.log(getFuncName());

    jQuery('#flash_seat_map_box_id').css('display', 'block');
    jQuery('#get_flash').css('display', 'none');
}
function important_note() {
    if (config['DEBUG']) console.log(getFuncName());
    
    var element = document.getElementsByClassName('important_note');
    //console.log(element);
    if (element.length > 0) {
        var important_note = element[0].textContent;
        
        // Replace newlines so we can decode it later
        //important_note = important_note.replace(/(\r\n|\n|\r)/gm, " ");
        
        // Fix: Encode component so we can pass it within url
        important_note = encodeURIComponent(important_note);
        if (config['DEBUG']) console.log(important_note);
        
        return important_note;
    }
}
function getFuncName(arg) {
    var caller;
    if (getFuncName.caller.name !== '') {
        caller = getFuncName.caller.name;
    }
    else {
        caller = arg;
    }
    
    return '\n' + '-'.repeat(80) + '\n' + 'PARENT ' + caller + '\n' + '-'.repeat(80);
}