// JavaScript Document 
var cities = [ "Adana", "Adıyaman", "Afyon", "Ağrı", "Aksaray", "Amasya", "Ankara", "Antalya", "Ardahan", "Artvin", "Aydın", "Balıkesir", "Bartın", "Batman", "Bayburt", "Bilecik", "Bingöl", "Bitlis", "Bolu", "Burdur", "Bursa", "Çanakkale", "Canakkale", "Çankırı", "Cankiri", "Çorum", "Corum", "Denizli", "Diyarbakır", "Düzce", "Edirne", "Elazığ", "Erzincan", "Erzurum", "Eskişehir", "Gaziantep", "Giresun", "Gümüşhane", "Hakkari", "Hatay", "Iğdır", "Isparta", "İstanbul", "Istanbul", "İzmir", "Izmir", "Kahramanmaraş", "Karabük", "Karaman", "Kars", "Kastamonu", "Kayseri", "Kırıkkale", "Kırklareli", "Kırşehir", "Kilis", "Kocaeli", "Konya", "Kütahya", "Malatya", "Manisa", "Mardin", "Mersin", "Muğla", "Muş", "Nevşehir", "Niğde", "Ordu", "Osmaniye", "Rize", "Sakarya", "Samsun", "Siirt", "Sinop", "Sivas", "Tekirdağ", "Tokat", "Trabzon", "Tunceli", "Şanlıurfa", "Sanliurfa", "Şırnak", "Sirnak", "Uşak", "Van", "Yalova", "Yozgat", "Zonguldak" ];
 
// set the cookie expiry time (days):
var setCookieExpiry = 180; 

function loadMore(params, source)
{
    var count = $('#' + source + ' li').size();
    if(count > 4){
        $('.more-' + source).show();
        $('#' + source + "_more").html("<span id=\"" + source + "_less_link\" class=\"show-less\"><a href=\"javascript:void(0);\" onclick=\"showLess('" + params + "', '" + source + "');\"><img src='/css/images/collapse-button.png' />&nbsp;Daha Az Sonu&#231; G&#246;ster...</a></span>");
    } else{
        document.getElementById(source + '_loading').style.display = 'inline';
        params_str = "target=" + source + "&params=" + params;
        $.get('/web_sources/load_more.php?' + params_str, function(data) {
            $('#' + source + ' ul').append(data);
            document.getElementById(source + '_loading').style.display = 'inline';
            $('#' + source + "_more").html("<span id=\"" + source + "_less_link\" class=\"show-less\"><a href=\"javascript:void(0);\" onclick=\"showLess('" + params + "', '" + source + "');\"><img src='/css/images/collapse-button.png' />&nbsp;Daha Az Sonu&#231; G&#246;ster...</a></span>");
        });
    }

    window.scrollBy(0,50);
}

function showLess(params, source)
{
    $('.more-' + source).hide();
    $('#' + source + "_more").html("<img id='" + source + "_loading' class=\"load_more_image\" src=\"/images/ajax-loading.gif\" width=16 alt=\"\" style=\"display:none\"/><span id=\"" + source + "_more_link\"><a href=\"javascript:void(0);\" onclick=\"loadMore('" + params + "', '" + source + "');\"><img src='/css/images/expand-button.png' />&nbsp;T&#252;m Sonu&#231;lar&#305; G&#246;ster...</a></span></div>");

    intY = document.getElementById(source).offsetTop;
    intY -= 50;
    window.scrollTo(0,intY);
}

function loadMoreNMore(params, source)
{
    document.getElementById(source + '_loading').style.display = 'inline';
    params_str = "target=" + source + "&params=" + params;
    $.get('/web_sources/load_more.php?' + params_str, function(data) {
        $('#' + source + ' ul').append(data);
        $('.more-' + source).show();
        document.getElementById(source + '_loading').style.display = 'inline';
        $('#' + source + "_more").html("<span id=\"" + source + "_less_link\" class=\"show-less\"><a href=\"javascript:void(0);\" onclick=\"showLess('" + params + "', '" + source + "');\"><img src='/css/images/collapse-button.png' />&nbsp;Daha Az Sonu&#231; G&#246;ster...</a></span>");
        window.scrollBy(0,50);
    });
}

function loadMoreGeneric(params, source)
{
    $('.more-' + source).show();
    $('#' + source + "_more").html("<span id=\"" + source + "_less_link\" class=\"show-less\"><a href=\"javascript:void(0);\" onclick=\"showLessGeneric('" + params + "', '" + source + "');\"><img src='/css/images/collapse-button.png' />&nbsp;Daha Az Sonu&#231; G&#246;ster...</a></span>");
    window.scrollBy(0,50);
}

function showLessGeneric(params, source)
{
    var inner = "<img id='" + source + "_loading' class=\"load_more_image\" src=\"/images/ajax-loading.gif\" width=16 alt=\"\" style=\"display:none\"/><span id=\"" + source + "_more_link\"><a href=\"javascript:void(0);\" onclick=\"loadMoreGeneric('" + params + "', '" + source + "');\"><img src='/css/images/expand-button.png' />&nbsp;T&#252;m Sonu&#231;lar&#305; G&#246;ster...</a></span></div>";
    $('#' + source + "_more").html(inner);
    $('.more-' + source).hide();
    intY = document.getElementById(source).offsetTop;
    intY -= 50;
    window.scrollTo(0,intY);
}

// function that writes the list order to a cookie
function setCookie(cookieName, cookieValue) {
    // save custom order to cookie
    $.cookie(cookieName, cookieValue, {
        expires: setCookieExpiry,
        path: "/"
    });
}

// function that restores the sidebar list order from a cookie
function restoreOrder(cookieName) {
	
    /*  get the list of widget ID's from the cookie
	
		for each widgetID in the cookie{
			find the widget and copy it to temp
			remove the original widget
			append the copy at the end of the column
		}*/ 


    // fetch the cookie value (saved order)
    var cookie = $.cookie(cookieName);
    if (!cookie) {
        //setCookie("layout-manager","w-photos:1:1,w-videos:1:0,w-news:1:0,w-microblogs:1:0,w-social:1:0");
        //cookie = $.cookie(cookieName);
        return;
    }
    // make array from saved order
    var cookieWidgetIDs = cookie.split(",");
		
    var widgetAttributes = cookieWidgetIDs[0].split(":");
    // widgetAttributes[0] = widgetId
    // widgetAttributes[1] = isVisible
    // widgetAttributes[2] = isMaximized
		
    // CURRENTLY IT DOES NOT CHECK IF IT IS VISIBLE OR MINIMIZED
    // THIS WILL BE HANDLED WITH PHP
		
    for (var i = 0, n = cookieWidgetIDs.length; i < n; i++) {
		
        widgetAttributes = cookieWidgetIDs[i].split(":");

        $currentWidget = $('#sortable-temp').children("#" + widgetAttributes[0]);
			
        // if the widget is closed in the cookie, close it before restoring
        if( widgetAttributes[1] == 0){
            $currentWidget.find(".w-close").trigger("click");
        }
        else{
            $('#sortable').append($currentWidget);
            $currentWidget.fadeIn();
        }
			
			
    /*
			// if the widget is minimized in the cookie, minimize it before restoring
			if( widgetAttributes[2] == 0){
				$currentWidget.find(".w-minimize").trigger("click");
			}
			else{
				$currentWidget.find(".w-maximize").trigger("click");
			}
			*/
			
    /*
			// find the widget and copy it to temp
			var temp = $('#sortable').children("#" + widgetAttributes[0]);
		
			//remove the original widget
			$('#sortable').children("#" + widgetAttributes[0]).remove();
		
			//append the copy at the end of the list
			$("#sortable").append(temp);
			*/
    }
}
 
 
// Set Cookie whenever a widget is maximized / minimized or dragged 
function updateLayoutManager(){
	
    var widgetArray = $("#sortable").sortable("toArray");
	
    /* cookie will contain string #widgetId / boolean isVisible / boolean isMaximized */
	
    /* for each widget find out if collapsed and visible */
    for(var i=0; i<widgetArray.length; i++){
			
        var currentWidgetId = $("#"+ widgetArray[i]);
			
        // if widget is visible
        if( $(currentWidgetId).is(':visible') ) {
            widgetArray[i] += ":1";
        }
        else {
            widgetArray[i] += ":0";
        }
				 
        // if widget is maximized
        if( $(currentWidgetId).children(".w-content").is(':visible') ) {
            widgetArray[i] += ":1";
        }
        else {
            widgetArray[i] += ":0";
        }
    }
    setCookie("layout-manager-sortable", widgetArray);
	
	
    var tempArray = [];
	
    // since we have an extra div when all the filters are loaded (Loading... div), it needs to be spliced from the array
    var loading_widget_found = -1;
	
    var tempSize = $('#sortable-temp .widget').length;
    $("#sortable-temp .widget").each(function(i,val){
        var $id = $(this).attr("id");
        if($id){
            tempArray[i] = $id + ":0:0";
        }
        else{
            loading_widget_found = i;
        }
    });
	
    // splicing the first unknown element from the array
    if(loading_widget_found != -1){
        tempArray.splice(loading_widget_found,1);
    }
	
    setCookie("layout-manager-temp", tempArray);
	
	
    var combinedArray = widgetArray + "," + tempArray;
    setCookie("layout-manager", combinedArray);
}
	 

$(function(){


    /*
** Setup Layout Manager 
*/

    // read the layout from the cookie and move the enabled ones to the #sortable from #sortable-temp
    //	restoreOrder("layout-manager");
	
	
    $("#sortable").sortable({
        placeholder: 'ui-state-highlight',
        handle: '.w-header',
        opacity: 0.6,
        revert: 150,
        update: updateLayoutManager
    });
	
	 

    /*
** Widget Controls - Maximize, Minimize & Close
*/
    /* append widget controls if JS is enabled */
//    $(".w-header").append('<div class="w-controls"><div class="w-maximize on"></div><div class="w-minimize"></div><div class="w-close"></div></div>');
	
    $(".w-header").hover( 	function(){
        $(".w-controls",this).stop().animate({
            opacity: 1
        },300);
    },
    function(){
        $(".w-controls",this).stop().animate({
            opacity: 0
        },300);
    });
 
    $('.w-minimize').click(function(){
        var wHeader = $(this).parents('.w-header');
		
        $(this).siblings(".w-maximize").toggleClass("on");
        $(this).toggleClass("on");
		
        $(this).parents('.widget').children('.w-content').slideToggle("300", function(){
            wHeader.toggleClass("rc");
            updateLayoutManager();
        });
		
    });
 
    $('.w-maximize').click(function(){
        var wHeader = $(this).parents('.w-header');
		
        $(this).siblings(".w-minimize").toggleClass("on");
        $(this).toggleClass("on");
		
        $(this).parents('.widget').children('.w-content').slideToggle("300", function(){
            wHeader.toggleClass("rc");
            var ck = $.cookie('google_ref_search');
            if (!ck) {
                updateLayoutManager();
            }
        });
		
    });
 
    $('.w-close').click(function(){
        // fade out the widget and append it to the #sortable-temp
        $(this).parents('.widget').fadeOut('300').appendTo("#sortable-temp");
		
        // update the checkbox in the sidebar
        var checkboxClass = "." + $(this).parents('.widget').attr('id');
        $('#w-settings').find(checkboxClass).find('a').removeClass('on');
		
        updateLayoutManager();  // NOTICE!!! - isToggled also gets set to false when the widget is closed
    });
	
	
    /* Hover on Styles */
    $('.w-close').hover(function(){
        $(this).css("background-position","-73px 0");
    },
    function(){
        $(this).css("background-position","-30px 0");
    });
	
    $('.w-minimize').hover(function(){
        $(this).css("background-position","-60px 0");
    },
    function(){
        $(this).css("background-position","-16px 0");
    });
	
	
    $('.w-maximize').hover(function(){
        $(this).css("background-position","-43px 0");
    },
    function(){
        $(this).css("background-position","0 0");
    });
	
	
	
	
    /*
** Search 
*/ 
    /* Focus & Blur */
    var adSoyadDefault = $(".adsoyad").attr("value");
	
    $(".adsoyad").focus(function(){
        if($(this).attr("value") == adSoyadDefault) $(this).attr("value", "");
    });
    $(".adsoyad").blur(function(){
        if($(this).attr("value") == "") $(this).attr("value", adSoyadDefault);
    });
	
	
    var sehirDefault = $(".sehir").attr("value");
	
    $(".sehir").focus(function(){
        if($(this).attr("value") == sehirDefault) $(this).attr("value", "");
    });
    $(".sehir").blur(function(){
        if($(this).attr("value") == "") $(this).attr("value", sehirDefault);
    });
	
	
    /* Visualization */
    $('input.sehir').focus(function(){
        $(this).addClass("focus-sehir");
    }); //css({'border-left':'1px solid #333','color':'#333'}); });
    $('input.sehir').blur(function(){
        $(this).removeClass("focus-sehir");
    }); //css({'border-left':'none','color':'#aaa'}); });

    $('input.adsoyad').focus(function(){
        $(this).addClass("focus-adsoyad");
    })//.css({'border-right':'1px solid #333','color':'#333'}); });
    $('input.adsoyad').blur(function(){
        $(this).removeClass("focus-adsoyad");
    })//.css({'border-right':'1px solid #E0E0E0','color':'#aaa'}); });
 
 
    /* Autocomplete */
    $('.sehir').autocomplete(cities);
	
	
		
    /* Anasayfa Search */
    $('#anasayfa .search').hover(	function(){
        $(this).addClass('search-hover');
    },
    function(){
        $(this).removeClass('search-hover');
    });
	
    /* Anasayfa Footer */
    $('html').mousemove(function(){
        $('#anasayfa-footer').fadeIn(1500);
        $('#front-page-imgs').fadeIn(1500);
    });
	
		
    /*
** Settings Widget 

	var currentWidgetId;
	
	// if widgets are visible, update the checkbox icon
	$('#w-settings li').each( function(){
		 currentWidgetId = '#'+$(this).attr('class');
		 if ( $(currentWidgetId).is(':visible') ){
			$(this).children('a').addClass('on'); 
		 }
	});
*/

    $('#w-settings li a').click( function(){
		
        currentWidgetId = '#'+$(this).parents('li').attr('class');
										  
        if( $(this).hasClass('on') ){
		
            $(currentWidgetId).find('.w-close').trigger('click');
        }
        else{
			
            // prepend this widget to top of the column
            $(currentWidgetId).prependTo('#sortable').fadeIn(function(){
                updateLayoutManager();
            });
			 
            // setup settings widget
            $(this).toggleClass('on');
        }
		
        return false;
		
										  
    });


    /*
** Sidebar Widget Overwrites
*/
	
//    $('#sidebar .widget').find('.w-maximize').trigger('click');
    $('#sidebar .w-controls').hide();

    /*
	$('#sortable .w-header').live("mousedown",function(){
	  $('#sortable .w-content').slideUp("50");
	});
	
	$('#sortable .w-header').live("mouseup",function(){
	  $('#sortable .w-content').slideDown("50");
	}); 
	*/

 
    var cookie = $.cookie("cached_widgets");
    if (cookie) {
        var cachedWidgetIds = cookie.split(":");
	
        var currentCachedWidget = "";
	
        for (var i = 0; i < cachedWidgetIds.length; i++) {
            currentCachedWidget = "#" + cachedWidgetIds[i] + " .w-maximize";
            $(currentCachedWidget).trigger('click');
        }
    }
	
    $.cookie("cached_widgets", "");

	
	
	
	
    /*
** Feedback Form - Sidebar

	$('#results-page').append('<a href="/email/contact.php" id="feedback-button" class="ceebox" rel="width:600 height:600">iletişim</a>').hide().fadeIn(); 


	$('#feedback-button').hover(
      function () {
        $(this).animate({ width: "95px"}, {queue:false, duration:300} ); 
      }, 
      function () {
       $(this).animate({ width: "65px"}, {queue:false, duration:300 } ); 
      }
    ); 
  	$('.ceebox').ceebox();
*/


    /*
** Settings Widget Helpers
*/
/*
    var helperText = [
    ["w-photos", ""],
    ["w-social", "Facebook, Yonja, MySpace, LiveSpaces, Netlog, Hi5, Bebo"],
    ["w-microblogs", "Twitter, Friendfeed"],
    ["w-news", ""],
    ["w-blogs", ""],
    ["w-videos", "Youtube, GoogleVideo"],
    ["w-business", "Xing, LinkedIn"],
    ["w-school", "MezunBul"],
    ["w-wikis", "Ekşisözlük, Wikipedia, İTÜSözlük , UludağSözlük"],
    ["w-forums", ""],
    ["w-shopping", "GittiGidiyor, HepsiBurada, Sahibinden, Araba.com, Idefix.com"],
    ["w-music", "Pandora"],
    ["w-art", "Flickr, FotoKritik, Antoloji"],
    ["w-books", ""],
    ["w-patents", ""],
    ["w-documents", "PDF, Word, Excel Belgeleri"],
    ["w-google", ""]
    ];
	
    var $settingsWidget = $("#w-settings ul");
    var widgetClass = "";
    var widgetTitle = "";
	
    for(var i=0; i<17; i++){
		
        widgetClass = "." + helperText[i][0];
        widgetTitle = helperText[i][1];
        $(widgetClass,$settingsWidget).find("a").attr("title",widgetTitle);
        $(widgetClass,$settingsWidget).find("a").attr("alt",widgetTitle);
    }



    $('.w-settings li a').tooltip({
        track: true,
        delay: 0,
        showURL: false,
        showBody: " - ",
        fade: 250
    });
*/



    /*
** Footer Contact Form
*/


    $('#footer-contact .f-input').focus(function(){
        $(this).addClass('focused');
    });
    $('#footer-contact .f-input').blur(function(){
        $(this).removeClass('focused');
    });
 
    $('#footer-contact textarea').focus(function(){
        $(this).addClass('focused');
    });
    $('#footer-contact textarea').blur(function(){
        $(this).removeClass('focused');
    });
 

    $('#footer-contact #f-submit').hover(	function(){
        $(this).addClass('focused');
    },
    function(){
        $(this).removeClass('focused');
    });
	
	
	
	
/*
    var loader = $('<div id="loader"><img src="/images/ajax-loading.gif" alt="loading..." /></div>')
    .css({
        position: "relative",
        top: "1em",
        left: "25em"
    })
    .appendTo("body")
    .hide();
    $().ajaxStart(function() {
        loader.show();
    }).ajaxStop(function() {
        loader.hide();
    }).ajaxError(function(a, b, e) {
        throw e;
    });
*/

    if($('#footer-contact').length != 0){
        var v = $("#footer-contact").validate({
            submitHandler: function(form) {
                $(form).ajaxSubmit({
                    target: "#footer-form-result"
                });
            }
        });
    }
	
    $('#footer-contact input, #footer-contact textarea').hover(	function(){
        $(this).addClass('hovered');
    },
    function(){
        $(this).removeClass('hovered');
    });
	
});

$('#footer-contact').submit(function() {
    var name = $("input[name=f-name]").val();
    var email = $("input[name=f-email]").val();
    var body = $("textarea[name=f-message]").val();

    $.get("/email/contact-action.php", { 
        name: name,
        email: email,
        body: body
    }, function(data){
        if(data != ""){ $('#contact-info').html('<br/>' + data); }
    });

    return false;
});

$(document).ready(function () {
    if($('#floating').length != 0){
    $("img.lazy").lazyload({
        placeholder : "css/images/grey.gif",
        effect : "fadeIn"
    });

    var top = $('#floating').offset().top - parseFloat($('#floating').css('marginTop').replace(/auto/, 0)) - 10;
    $(window).scroll(function (event) {
    // what the y position of the scroll is
    var y = $(this).scrollTop();
//    var footer = $('#footer').offset().top - 560;

    // whether that's below the form
//    if (y >= top && y < footer ) {
    if (y >= top) {
      // if so, ad the fixed class
      $('#floating').addClass('fixed');
    } else {
      // otherwise remove it
      $('#floating').removeClass('fixed');
    }
    });
    }
});



