﻿/** disqus plugin **/
// DISQUS vars.
var disqus_shortname = 'microsoft-techdays-kr';
var disqus_identifier = '';
var disqus_url = '';

// Leave a comment/cancel.
$('.comment-forum .comment').live('click', function () {
    // Firefox? Bad firefox.
    if ($.browser.mozilla && window.disqus_loaded) {
        return true;
    }
    // reset, close other comment forums
    $('.disqus_thread').empty();
    $('.commentarea').slideUp();

    // Init DISQUS.
    disqus_identifier = $(this).data('disqus-identifier');
    //disqus_url = $(this).attr('href');

    // DISQUS requires each thread to have the ID #disqus_thread.
    $entry = $(this).parents('div.comment-forum');

    if ($("#" + $entry.attr('id')).find('.commentarea').is(':hidden')) {
        $('#disqus_thread').removeAttr('id');
        $entry.find('div.disqus_thread').attr('id', 'disqus_thread');

        // Load DISQUS script, if not already loaded.
        if ($entry.find('div.disqus_thread .dsq-reply').length == 0) {
            var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
            dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
            (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
        }
        $("#" + $entry.attr('id') + " .commentarea").slideDown();
        $("a.nocomment").hide(); //reset others
        $("a.comment").show(); //reset others
        $("#" + $entry.attr('id') + " a.comment").hide();
        $("#" + $entry.attr('id') + " a.nocomment").show();
    } else {
        $("#" + $entry.attr('id') + " a.nocomment").hide();
        $("#" + $entry.attr('id') + " a.comment").show();
    }

    return false;

});


(function () {
    var s = document.createElement('script'); s.async = true;
    s.type = 'text/javascript';
    s.src = 'http://' + disqus_shortname + '.disqus.com/count.js';
    (document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s);
} ());
/** /disqus **/




/*
 *	what does this do? boom
 */
$(document).ready(function () {

    //check if page is topics.aspx
    if (get_filename() === 'topics.aspx') {
        var id = getParameterByName("id");
        var paths = id.split("-");
        $('.video_embedded').css({ display: 'block' });
        if (paths[0] != 'devs') {
            $('.button-blue').css({ display: 'none' });
        }

    }

    /**
    $('.video_embedded2').jqm();
    $('a.watch-vid').live('click', function () {
    var id = $(this).parent().parent().attr('id');
    $('#' + id + ' .video_embedded2').jqmShow();
    return false;
    });**/

    /* * -- accordion -- * */
    jQuery('#accordion').accordion({
        autoHeight: false,
        icons: { header: "ui-icon-circle-plus-e", headerSelected: "ui-icon-circle-minus-s" }
    });
    /* * -- /accordion -- * */

    /* -- newsletter subscription area -- */
    //show
    $("#subscribe").live('click', function () {
        //$("#toparea").css("height","230px");
        $("#subscribearea").slideDown("slow");
        $("#toparea").animate({ height: '230px' }, 500)

    });
    //hide
    $("#closearea").live('click', function () {
        $("#subscribearea").slideUp("slow");
        $("#toparea").animate({ height: '7px' }, 500)
    });

    /* * pseudo dropdown selection * */
    $("#countries").find(".li").hover(function () { $(this).css({ "background-color": "#f5f5f5" }); },
    function () {
        $(this).css({ "background-color": "#fff" });
    });
    $("#countries").live('click', function () {
        if ($("#countries .li").is(":hidden")) {
            $("#countries .li").slideDown()
        } else {
            $("#countries .li").hide();
        }
    });

    $(".country").live('click', function () {
        var mode = "staging"; //change to live if site is live!
        var domain = location.protocol + '//' + location.hostname;
        var country = $(this).attr('id');
        var folder = "techdays";
        if (mode === 'staging') {
            domain = "http://www.microsoft.com"
        }
        $("#countries .selected").text($(this).text());
        if (country.length > 0)
            window.location = domain + '/' + country + '/' + folder;
    });
    /* * -- END -- * */

    /* * -- show more speakers -- * */
    $(".show-more").live('click', function () {
        var total_hidden = $('#featured .hide').size();

        if (total_hidden > 0) {
            $('#featured .hide').each(function (index) {
                var separator = (index + 1) % 4;
                $(this).slideDown("slow");
                $(this).removeClass('hide');
                //console.log("index: "+index+" mod: "+separator);
                if (separator === 0) {
                    return false;
                }
            });

            var total_speakers = $('#featured .speaker').size();
            total_hidden = $('#featured .hide').size();
            if (total_hidden === 0) {
                $(".show-more").html("<span class='lbl-hide'>닫기</span>");
            }
        } else {
            // refresh featured section
            //$('#featured').load(get_filename() + " #featured");
            $('#featured .speaker').each(function (index) {
                if (index >= 4) {
                    $(this).addClass('hide');
                }
            });
            $(".show-more").html("<span class='lbl-show'>더 보기</span>");
            $('#featured .hide').slideUp("slow");
        }
    });
    /* * -- /show more -- * */



    // Set active class to current page
    $('a.main_navbar').each(function () {
        var avalue = $(this).attr('href');
        var lhref = location.href;
        lhref = lhref.replace("#", " ");
        var prevactive = $('#navbar').find('li a.active').parent().attr('class');
        var liclass = $(this).parent().attr('class');
        var current_subpage = get_filename();
        var parent_page = current_subpage.split("_", 1);
        parent_page[0] = parent_page[0].replace(/.\aspx/, '');

        if (lhref.search(avalue) > -1 || parent_page[0] === liclass) {
            //remove previously selected page
            $('li.' + prevactive).find('a').removeClass('active');
            $("#navbar li." + liclass).find('a').addClass("active");

            if (parent_page[0] === liclass) {
                $('ul#links li:not(ul.links-subtrack > li)').each(function () {

                    //if this sub link is selected
                    if ($(this).find('a').attr('id') + ".aspx" === current_subpage) {
                        $(this).addClass("selected");
                        $(this).find('ul.links-subtrack').css({ display: 'block' });
                    } else {
                        $(this).removeClass("selected");
                        $(this).find('ul.links-subtrack').css({ display: 'none' });
                    }

                });
            }


        } else if (current_subpage === 'topics.aspx') {
            //var id = getParameterByName("id");
            var track = getParameterByName("track");

            switch (track.toLowerCase()) {
                case "클라우드":
                    var current_topic = 'developers';
                    break;
                case "클라이언트":
                    var current_topic = 'developers_2';
                    break;
                case "스마트폰":
                    var current_topic = 'developers_3';
                    break;
                case "alm":
                    var current_topic = 'developers_4';
                    break;
                case "bi 솔루션 개발":
                    var current_topic = 'developers_5';
                    break;
                case "cloud":
                    var current_topic = 'itpros_cloud';
                    break;
                case "client":
                    var current_topic = 'itpros_client';
                    break;
                case "office 365":
                    var current_topic = 'itpros_office';
                    break;
                case "sql":
                    var current_topic = 'itpros_sql';
                    break;
                case "fun":
                    var current_topic = 'itpros_fun';
                    break;
            }

            $('ul#links li:not(ul.links-subtrack > li)').each(function () {
                $(this).find('ul.links-subtrack').css({ display: 'none' });
                //if this sub link is selected
                if ($(this).find('a').attr('id') === current_topic) {
                    $(this).addClass("selected");
                    $(this).find('ul.links-subtrack').css({ display: 'block' });
                } else {
                    $(this).removeClass("selected");
                    $(this).find('ul.links-subtrack').css({ display: 'none' });
                }



            });

        }

    });

    $("#links a.link-tab").live('click', function (e) {
        e.preventDefault();
        window.location = $(this).attr('id') + ".aspx";
    });

    // filter topics by subtrack
    $("a.filter-sub").live('click', function (e) {
        e.preventDefault();
        var parent_id = $(this).parent().parent().attr('id');
        var id = $(this).parent().attr('class');
        id = $.trim(id.replace(/default/, ''));
        //remove default sub
        $(this).parent().parent().find('li').removeClass('default');
        // select parent as default sub
        $(this).parent().addClass('default');
        $('.parent-subtrack').hide();
        $('#' + parent_id + '_' + id).css({ display: 'block' });

    });




    /* * -- schedule filtering -- * */
    // by default filters are all checked
    toggle_cb("check");
    //uncheck all
    $("#uncheck-all").live('click', function () {
        if ($(this).is(':checked'))
            toggle_cb("uncheck");
    });

    // filter schedule
    $("#filters .cb").live('click', function () {
        if ($(this).is(':checked') && $(this).attr("id") != "uncheck-all")
            $("#uncheck-all").removeAttr("checked");
    });

    $("#filter-sched").live('click', function () {
        var roles_level = [];
        var roles = [];
        var levels = [];
        var tracks = [];

        $("input[name='roles_level[]']:checked").each(function () { roles_level.push($.trim($(this).parent().text().toLowerCase())); });
        $("input[name='tracks[]']:checked").each(function () { tracks.push($.trim($(this).parent().text().toLowerCase())); });

        // separate roles, levels
        for (var j = 0; j < roles_level.length; j++) {
            var filter_val = roles_level[j].split(" - ", 2);
            roles.push(filter_val[0]);
            levels.push(filter_val[1]);
        }

        /*
        * if all filter checkboxes are unchecked,
        * force to check all and show all data
        */

        if (roles_level.length === 0 && tracks.length === 0) {
            toggle_cb("check");
        } else {

            $("#schedule .row").each(function (i) {
                if ($(this).hasClass("common")) {
                    //if common row show immediately
                    $(this).show();
                } else {
                    var row_id = (i + 1);
                    var row_div_id = "row_" + row_id;
                    var show_row = false;
                    var col_arr = [];
                    var col_ctr = 0;
                    $(this).attr("id", row_div_id);

                    // search each column from info row if matched
                    $(this).find('.col').each(function (x) {
                        var check_role_level = 0;
                        var check_track = 0;
                        var col_id = (x + 1);
                        var col_div_id = "row_" + row_id + "_col_" + col_id;
                        $(this).attr("id", col_div_id);
                        var temp_col = col_div_id;

                        // compare role on column data if match to selected/filtered roles array
                        $(this).find('.role').each(function (n) {
                            var this_role = $(this).text().toLowerCase();
                            var this_level = $("#" + col_div_id).find('.level').text().toLowerCase();
                            for (var m = 0; m < roles.length; m++) {
                                if (this_role === roles[m] && this_level === levels[m]) {
                                    check_role_level++;
                                }
                            }

                        });

                        // compare track on column data if match to selected/filtered tracks array
                        $(this).find('.track').each(function () {
                            check_track = check_match(check_track, $(this).text().toLowerCase(), tracks);
                        });

                        // if matched show column from this row
                        if (check_role_level > 0 || check_track > 0) {
                            ++col_ctr;
                            show_row = true;
                            col_arr.push(col_div_id);
                            // remove left padding for every first col of a row
                            if (col_ctr === 1 || (col_ctr - 1) % 4 === 0) {
                                if ((col_ctr - 1) % 4 === 0)
                                    temp_col = "row_" + row_id + "_col_" + (col_id + 1);

                                var pleft_val = "0px"
                            } else {
                                var pleft_val = "10px"
                            }
                            // adjust the top padding for the second data row
                            $("#" + temp_col).css({ 'padding-left': pleft_val });
                            if (col_arr.length > 1) {
                                if (col_ctr > 4) {
                                    $("#" + col_div_id).css({ 'padding-top': '30px' });
                                } else {
                                    $("#" + col_div_id).css({ 'padding-top': '60px', 'margin-top': '1px' });
                                }
                            }
                            $("#" + col_div_id).show();
                        } else { $("#" + col_div_id).hide(); }
                    }); //loop through column;


                    // if any column data from this row matched, show row
                    if (show_row) {
                        // if more than one column adjust styling
                        if (col_arr.length === 1) {
                            if ($("#" + col_arr[0]).hasClass('adjust')) {
                                $("#" + col_arr[0]).removeClass('adjust');
                                $("#" + col_arr[0]).css({ 'margin-top': '45px', 'padding-right': '15px', 'min-height': '110px' });
                            }
                        } else {
                            //check if it has adjust class
                            for (var z = 0; z < col_arr.length; z++) {
                                if ($("#" + col_arr[z]).hasClass('adjust') === false) {
                                    $("#" + col_arr[z]).addClass('adjust');
                                    $("#" + col_arr[z]).css({ 'margin-top': '1px', 'min-height': '380px', 'padding-right': '10px' });
                                }
                            }
                        }
                        $("#" + row_div_id).show();
                    } else { $("#" + row_div_id).hide(); }

                } //end if row has class;
            }); //loop through row;

        } //end if;
    });

    //check for match schedule
    function check_match(count_match, name, arr) {
        var match = jQuery.inArray(name, arr);
        if (match >= 0) {
            count_match++;
        }
        return count_match;
    }
    //toggle checkbox if checked, uncheck... vice-versa;
    function toggle_cb(status) {
        $("#filters").find('input:checkbox').each(function () {
            if ($(this).attr('id') != 'uncheck-all') {
                if (status === 'uncheck') {
                    $(this).removeAttr('checked');
                } else {
                    $(this).attr('checked', 'checked');
                }
            }

        });

    }

    /**
    // show all topic files
    if ($(".hidden_fileList").length) {
    var topic_files = $(".hidden_fileList").val().toLowerCase().split(",");
    for (var x = 0; x < topic_files.length; x++) {
    $.get("talks/" + topic_files[x], function (data) {
    $("#talk-content").append(data + "<br /><br />");
    });
    }
    }**/

    // populate filter selection for topics page
    /**if (get_filename() === 'topics.aspx') {
        if ($(".hidden_topicFiles").length > 0) {
            var topic_files = $(".hidden_topicFiles").val().toLowerCase().split(",");
            var topics_optgroup = [];
            var group    = $.trim($("#txtGroup").val().toLower());
            var trackNum = $.trim($("#txtTrackNum").val().toLower());
            var track    = $.trim($("#txtTrack").val());

            for (var x = 0; x < topic_files.length; x++) {
                $.get($($dir_path).val() + topic_files[x], function (data) {
                    console.log($('.hidden_topicFolder').val() + topic_files[x]);
                    $(".topic-list").append(data + "<br /><br />");
                });
            }


            $(".topic-list .topic").each(function (i) {
                var current_subtrack = $.trim($(this).find('.subtrack').text());
                var topic_id = $(this).attr('id');
                var topic_txt = $(this).find('h2').text();
                generateFilterList(topics_optgroup, topic_id, topic_txt, current_subtrack, '#event_topics');

            });



        }
    }**/
    /** /show all **/


    //preload listing for topic filter
    var topics_optgroup = [];
    $(".topic-list .topic").each(function (i) {
        var current_subtrack = $.trim($(this).find('.subtrack').text());
        var topic_id = $(this).attr('id');
        var topic_txt = $(this).find('h2').text();
        generateFilterList(topics_optgroup, topic_id, topic_txt, current_subtrack, '#event_topics');

    });

    $("#event_topics").live('change', function () {
        if ($("option:selected", this).val().toLowerCase() === 'show all') {
            $(".topic-list").find('.parent-subtrack, .topic').show();
        } else {
            var id = $("option:selected", this).val();
            $(".topic-list").find('.parent-subtrack, .topic').hide();
            $("#" + id).parent().show();
            $("#" + id).show();
        }
    });


    /* * -- /schedule filtering -- * */

    /* * -- twitter live stream -- * */
    $('#tweets_live_stream').twitterSearch({
        term: 'KRTechDays',
        title: '',
        css: {
            a: { color: "#26ade4" },
            img: { width: '50px', height: '50px', margin: '4px 10px 0 0', border: '1px solid #d3d3d3' },
            frame: { border: '0', borderRadius: '0px', '-moz-border-radius': '0px', '-webkit-border-radius': '0px' },
            tweet: { margin: '5px 0 0 0', padding: '5px 0px 10px 10px', textAlign: 'left', clear: 'left', 'min-height': '60px' }
            // user: { padding: '0px 0px 0px 5px', fontWeight: 'bold' }
        },
        // no fade
        animOut: { opacity: 1 },
        avatar: true,
        anchors: true,
        bird: false,
        colorExterior: 'white',
        colorInterior: 'white',
        pause: true,
        time: true,
        timeout: 7000


    });

    /* * -- /twitter live stream -- * */



    //http://api.flickr.com/services/feeds/photoset.gne?set=72157625775129959&nsid=53913614@N03&
    $.getJSON("http://api.flickr.com/services/feeds/photoset.gne?set=72157625775129959&nsid=53913614@N03&lang=en-us&format=json&jsoncallback=?", function (data) {
        $.each(data.items, function (i, item) {
            $("<img style='width: 72px; height: 72px; margin: 12px 12px 0 0; border: 1px solid #d3d3d3;'/>").attr("src", item.media.m.replace("_m", "_s")).appendTo("#flickr_gallery")
			.wrap("<a href='" + item.link + "'></a>");
        });
    });

    // photo slider
    $('#slider1, #slider2, #slider3').nivoSlider({
        effect: 'fade',
        controlNavThumbs: true,
        manualAdvance: true,
        directionNav: false

    });




    //show BING map
    if ($('#location_map').length) {
        //GetMap(1.3109644208789035, 103.83617372135146);
        GetMap(1.293358, 103.857132);
    }

    // Audio player for event pages
    if ($('.audio-player').length) {
        $f("audio-1", "http://releases.flowplayer.org/swf/flowplayer-3.2.7.swf", {
            plugins: {
                controls: {
                    fullscreen: false,
                    height: 30,
                    autoHide: false
                }
            },
            clip: {
                autoPlay: false,
                onBeforeBegin: function () {
                    $f("player").close();
                }
            }
        });
    }

    /* * -- END -- * */
});


// Bing Search focus and blur effect
$(document).ready(function(){
	$('#WLSearchBoxInput').focus(function(){
	    if ($(this).val() == '검색')
			$(this).val('');
	});

	$('#WLSearchBoxInput').blur(function(){
		if ($(this).val() == '')
		    $(this).val('검색');
	});
});

function generateFilterList(topics_optgroup, topic_id, topic_txt, current_subtrack, $filter_id) {
    var html_option = "<option value='" + topic_id + "'>" + topic_txt + "</option>";
    var html_optgrp = "<optgroup label='" + current_subtrack + "'></option>";

    if (current_subtrack.length > 0) {
        if ($.inArray(current_subtrack, topics_optgroup) === -1) {
            topics_optgroup.push(current_subtrack);
            $($filter_id).append(html_optgrp);
        }

        $($filter_id).find('optgroup[label*="' + current_subtrack + '"]').append(html_option);
    } else {
        $($filter_id).append(html_option);
    }
}

function getParameterByName(name) {
    var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
    return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}

function WLSearchBoxButton_onclick() {
    var Url = "http://www.bing.com/search?q=";
    var q = document.getElementById("WLSearchBoxInput").value;
    window.location.href = Url + q;
}

function get_filename() {
	var url = document.location.href;
	url = url.substring(0, (url.indexOf("#") == -1) ? url.length : url.indexOf("#"));
	url = url.substring(0, (url.indexOf("?") == -1) ? url.length : url.indexOf("?"));
	url = url.substring(url.lastIndexOf("/") + 1, url.length);
	return url.toLowerCase();
}

var map = null;
var GetMap = function (lat, lng) {
    map = new VEMap('location_map');
    map.LoadMap(new VELatLong(lat, lng), 16, 'r');
    SetPinOffset();
}

var SetPinOffset = function () {
    var myPin = new VEShape(VEShapeType.Pushpin, map.GetCenter());
    var myCustomPin = new VECustomIconSpecification();
    myPin.SetCustomIcon('<img src="images/map-pin.png" style="position:relative;left:-24px;top:-72px"></img>');
    map.AddShape(myPin);
}



function get_absolute_path() {
    var loc = window.location;
    var pathName = loc.pathname.substring(0, loc.pathname.lastIndexOf('/') + 1);
    return loc.href.substring(0, loc.href.length - ((loc.pathname + loc.search + loc.hash).length - pathName.length));
}
