﻿(function($) {

$(document).ready(function() {

    if (typeof (window['disclaimersObj']) != "undefined") {
        disclaimersObj = disclaimersObj.replace(/\t/g, '');
        disclaimersObj = disclaimersObj.replace(/\n/g, '');
        disclaimersObj = disclaimersObj.replace(/\r/g, '');
        disclaimersObj = disclaimersObj.replace(/&lt;/g, '<');
        disclaimersObj = disclaimersObj.replace(/&gt;/g, '>');
        obj = $.parseJSON(disclaimersObj);
    }

    $('#selLandFlwOut li a').click(function() {
        if (typeof (_gaq) !== 'undefined') {
            var new_country_url = $(this).attr('href');
            _gaq.push(['_trackEvent', 'Disclaimer', 'Exit', new_country_url]);
        }
    });


    if ($().nyroModal) {
        $('.popupcontact').nyroModal({
            width: 650, //default Width If null, will be calculate automatically
            height: 580
        });
    }

    $('.scButton[name=buttonCreate]').click(function() {
        $('div.content-area fieldset.summary').hide();
        $('div.content-area div.loading').fadeIn('slow');
        return false;
    });

    $('.scButton[name=buttonDelete]').click(function() {
        $('.confirmPanel').hide();
        $('.content-area div.loading').fadeIn('slow');
        return false;
    });


    if ((typeof (_gaq) !== 'undefined') && (($('.contactFormLocation').length > 0) || ($('.contactFormTopic').length > 0))) {
        $('.scfSubmitButton').mouseup(function() {
            _gaq.push(
				['_setCustomVar', 1, 'Location', $('.contactFormLocation select option:selected').text(), 2]
			);
            _gaq.push(['_trackPageview']);
            _gaq.push(
				['_setCustomVar', 2, 'Topic', $('.contactFormTopic select option:selected').text(), 2],
				['_trackEvent', 'Contact form', 'Submit']
			);
        });
    }

    if (typeof (countrySite) !== 'undefined') {
        site = (countrySite.search('nycomed') !== -1) ? '' : '/' + countrySite;
    } else {
        site = '';
    }

    $('a.media').mouseup(function() {
        if (typeof (_gaq) !== 'undefined') {
            file_url = $(this).attr('href');
            file_array = file_url.split('/');
            file_name = file_array[file_array.length - 1];
            _gaq.push(['_trackEvent', 'Download', file_name]);
            _gaq.push(['_trackPageview', site + '/virtual/downloads/' + file_name]);
        }
    });

    if ((typeof (track404) !== 'undefined') && (typeof (_gaq) !== 'undefined')) {
        if (track404) {
            _gaq.push(
				['_setCustomVar', 3, 'Error', '404', 3],
				['_trackPageview']
			);
        }
    }

    if ((typeof (results_number) !== 'undefined') && (typeof (_gaq) !== 'undefined')) {
        r_n = "'" + results_number + "'";
        _gaq.push(
			['_setCustomVar', 4, 'No. of search results', r_n, 3],
			['_trackPageview']
		);
    }

    if (($('#page-editor-versions').length > 0) && ($('#page-editor-versions a.versions-close').length > 0)) {
        $('#page-editor-versions a.versions-close').click(function() {
            $('#page-editor-versions').toggle();
        });
    }
    $("#checkboxlogin .signin input").click(function() {
        if ($('.checkbox input:not(:checked)').length > 0) {
            $('.notChecked').fadeIn();
            return false;
        }
    });

    $(".checkboxlogin .btnLogin").click(function() {
        if ($('.cbLoginCheckBox input:not(:checked)').length > 0) {
            $('.notChecked').fadeIn();
            return false;
        }
    });

    var selTab = 0;
    $("#login-tabs>.login-box").each(function(index) {
        if ($(this).attr('id') === $(".jshow").val()) {
            selTab = index;
        }
    });

    $("#login-tabs").tabs({ selected: selTab });

    //Fix the first boxTeaser in PE
    $(".stage2rows div:first-child").addClass('firstRowTeaser');

    $("#confirmFieldDelete .button").click(function() {
        var confirmFieldDelete = $('#confirmFieldDelete');
        confirmFieldDelete.hide();
        return true;
    });
});

})(jQuery);


function preparePrint(winName, Wwidth, Wheight) {
    wleft = parseInt((parseInt(screen.width) - Wwidth) / 2);
    wtop = parseInt((parseInt(screen.height) - Wheight) / 2);
    printWin = window.open(jQuery(location).attr('href'), winName, "channelmode=0, directories=1, fullscreen=0, location=0, menubar=1, resizable=1, scrollbars=1, status=1, titlebar=1, toolbar=1,width=" + Wwidth + ",height=" + Wheight + ", left=" + wleft + ", top=" + wtop);
    printWin.focus();
}

function cleanUpPreview() {
    window.close();
}

function openExternalLink(url, type, target) {
    jQuery.each(obj, function(i, val) {
        if (val.cssclass == type) {
            notice = jQuery('.notice').length;
            if (notice > 0) {
                var cur = jQuery('.notice .content .wrap');
                var cur0 = jQuery('.notice .content');
                jQuery(cur).find('h2').empty().html(val.title);
                jQuery(cur).find('.text').empty().html(val.text);
                jQuery(cur).find('.notice-button a').attr('href', url);
                jQuery(cur).find('.notice-button a').attr('target', target);
            } else {
                elm = jQuery('body').append('<div class="notice"><div class="bg"></div></div>');
                elm = jQuery('.notice .bg').append('<div class="content"><div class="wrap"></div></div>');
                elm = jQuery('.notice .content').append('<a class="close" href="javascript:hideNotification()"><img alt="Close" src="/img/notice-close.png"></a>');
                elm = jQuery('.notice .content div.wrap').append('<h2>' + val.title + '</h2>');
                elm = jQuery('.notice .content div.wrap').append('<div class="text">' + val.text + '</div>');
                elm = jQuery('.notice .content div.wrap').append('<p class="notice-button"><a target="' + target + '" href="">Ok</a></p>');
                jQuery('.notice-button a').attr('href', url);
                jQuery('.notice-button a').click(function() {
                    if (typeof (_gaq) !== 'undefined') {
                        var cur_url = document.location.href;
                        var new_url = jQuery('.notice-button a').attr('href');
                        _gaq.push(['_trackEvent', 'Disclaimer', 'Exit', new_url]);
                    }
                    hideNotification();
                });
                prepared = false;
            }
        }
    });

    showNotification(true);

}

function prepare() {
    if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 7 && parseInt(jQuery.browser.version, 10) > 4) {
        img = jQuery(".notice .content .close img");
        var styles = {
            'width': img.width() + 'px',
            'height': img.height() + 'px',
            'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + img.attr('src') + "', sizingMethod='scale')"
        };
        img.css(styles).attr('src', '/img/x.gif');
        prepared = true;
    }
}

// ## NOTIFICATION
function showNotification(closeable) {
    var maskHeight = jQuery(document).height();
    var maskWidth = jQuery(window).width();

    jQuery('.notice').css({ 'width': maskWidth, 'height': maskHeight });
    jQuery(".notice").show();
    jQuery(".notice .content .close").css("display", (closeable ? 'block' : 'none'));

    if (!prepared) { prepare(); }

    updatePosition();
}

function hideNotification() {
    jQuery(".notice").hide();
}

function updatePosition() {
    var margin = (jQuery(".notice .content").height() / 2) * -1;
    jQuery(".notice .content").css('margin-top', margin + 'px');
    if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 7 && parseInt(jQuery.browser.version, 10) > 4) {
        jQuery(".notice .content").css('top', (jQuery(window).height() / 2 + jQuery(window).scrollTop()) + 'px');
    }
    // IF TEXT CONTENT IS BIGGER THAN CLIENT HEIGHT, CHANGE IT
    if (jQuery(".notice .content").height() >= jQuery("html").height()) {
        jQuery(".notice").css("position", "absolute").css("height", jQuery(".notice .content").height() + 40);
    } else {
        jQuery(".notice").css("position", "fixed").css("height", "100%");
    }
}

/* contact form */
function getFormularDropListCustomChange(valueForShow, formID, idsForToShow) {
    __doPostBack('__Page', formID);
}

function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() !== false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}

function getLanguageCookie(cookieName) {
    // return  getCookie(name);
    var results = document.cookie.match('(^|;) ?' + cookieName + '=([^;]*)(;|$)');

    if (results)
        return (unescape(results[2]).toLowerCase());
    else
        return null;
}


function createCookie(cookieName, newEntry) {
	$.cookie(cookieName, newEntry, { expires: 30, path: '/',  secure: false});
    return true;
}

function deleteLanguageCookie(cookieName) {
    var cookie_date = new Date();
    cookie_date.setTime(cookie_date.getTime() - 1);
    document.cookie = cookieName += "=; expires=" + cookie_date.toUTCString();
    return true;
}

function is_string(input) {
    return typeof (input) == 'string';
}

function is_object(input) {
    return typeof (input) == 'object';
}

function removeLanguageCookie(site) {
    var existingSites = getLanguageCookie(cookieName);
    cookieName = 'rememberLanguage';

    var siteSearch = "|" + site + "#".toLowerCase();

    if (existingSites) {
        if (existingSites.indexOf(siteSearch) != -1) {
            var startIndex = existingSites.indexOf(siteSearch);
            var lastIndex = (existingSites.substring(startIndex + 1)).indexOf("|");
            var whatWeHave = existingSites.substring(startIndex, lastIndex + 2);

            existingSites = existingSites.replace(whatWeHave, "");

            if (existingSites.length > 0) {
                existingSites = "|" + existingSites;
            }
            createCookie(cookieName, existingSites);
        }
    }
}

function setLanguageCookie(param) {
    // var today = new Date();
    //  var nextMonth = new Date(today.getYear(), today.getMonth()+1, today.getDate());
    // setCookie(name, value, nextMonth);
    cookieName = 'rememberLanguage';
    site = jQuery("#rememberHome").val();

    if ((!site) || site == '' || (!param)) {
        return;
    }

    var url = "";
    if (is_string(param)) {
        url = param;
    } else {
        url = jQuery(param).attr('href');
    }

    if (!url || jQuery.trim(url) == "") {
        return;
    }
    var existingSites = getLanguageCookie(cookieName);

    var newEntry = "|" + site + "#" + url + "|".toLowerCase();
    var siteSearch = "|" + site + "#".toLowerCase();

    if (existingSites) {
        if (existingSites.indexOf(siteSearch) == -1) {
            var appendSettings = existingSites + site + "#" + url + "|";
            createCookie(cookieName, appendSettings.toLowerCase());
        }
        else   // the site is there, we need to redo the url
        {
            var startIndex = existingSites.indexOf(siteSearch);
            var lastIndex = (existingSites.substring(startIndex + 1)).indexOf("|");
            var whatWeHave = existingSites.substring(startIndex, lastIndex + 2);
            if (whatWeHave.toLowerCase() != newEntry.toLowerCase());
            {
                existingSites = existingSites.replace(whatWeHave, newEntry);
                createCookie(cookieName, existingSites);
            }
        }
    }
    else  // the cookie does not exist , we need to create it
    {
        createCookie(cookieName, newEntry);

    }
	//window.location.reload();
    return true;
}


// for Form Editing from Page Editor
function showConfirmFieldDeleteDialog(id, idHidden) {
    var confirmFieldDelete = document.getElementById('confirmFieldDelete');
    var hiddenInput = document.getElementById(idHidden);
    hiddenInput.value = id;
    confirmFieldDelete.style.display = 'block';
    return false;
}

function KeywordMatch(url) {
    var searchWords = document.getElementById('q').value ;

	if (searchWords) {
		var query = "?q=" + encodeURIComponent(searchWords);
		url = url + "" + query;

        var $target = jQuery('#searchResults');

        $target.load(url + ' .container > *',  function(){
            if ( typeof(featured_number) !== 'undefined' ) {
                $('.results-meta').hide();
            }
        });
	}
}
